Jhipster generator doesn't generate filter panel in UI - filter

I am using jhipster to generate CRUD for my web application.
by configuring jdl generator I expect to see search panel in UI for each entity. But it just generates EntityQueryService classes in backend,it works fine
and it is reachable in swagger-ui in the API docs page
Is there any UI library thing to help me pass parameters as expected format or any predicate filter panel ?
Thanks.

Finally I addded manual search panel as below :
<div class="container-fluid">
<div class="row">
<jhi-alert-error></jhi-alert-error>
<div class="col-sm-4">
<label for="field_billOrgType">organization</label>
<select id="field_billOrgType" ng-model="vm.searchModel.billOrgType">
<option ng-repeat="x in vm.Utilities" value="{{x.key}}">{{x.name}} - {{x.key}}</option>
</select>
</div>
</div>
</div>
My controller:
( function () {
'use strict';
angular
.module('ebppApp')
.factory('TmpBill', TmpBill);
TmpBill.$inject = ['$resource'];
function TmpBill($resource) {
var resourceUrl = 'api/tmp-bills/:id';
return $resource(resourceUrl, {}, {
'search': {
method: 'GET'
, isArray: true
, url: 'api/tmp-bills?:billOrgType',
params: {
billOrgType: '#billOrgType'
}
}
}
});
} })();
function search() {
TmpBill.search({
billOrgType: vm.searchModel.billOrgType ? "billOrgType.equals=" + vm.searchModel.billOrgType : ''
page: vm.page - 1,
size: vm.itemsPerPage,
sort: sort()
}, onSuccess, onError);
function sort() {
var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')];
if (vm.predicate !== 'id') {
result.push('id');
}
return result;
}
function onSuccess(data, headers) {
vm.links = ParseLinks.parse(headers('link'));
vm.totalItems = headers('X-Total-Count');
vm.queryCount = vm.totalItems;
vm.tmpBills = data;
// vm.page = pagingParams.page;
}
function onError(error) {
AlertService.error(error.data.message);
}
}

Related

v-for render after AJAX request

I have a main page containing a component called single-contact as below:
<el-row id="rowContact">
<!-- Contacts -->
<el-scrollbar wrap-class="list" :native="false">
<single-contact ref="singleContact"></single-contact>
</el-scrollbar>
</el-row>
And I want to dynamically render this component after AJAX polling, so in SingleContact.vue I use $axios and mounted() to request the data from the backend. And I want to render the component using v-for. I have my code as:
<template>
<div :key="componentKey">
<el-row id="card" v-for="contact in contacts" :key="contact.convUsername">
<div id="avatar" ><el-avatar icon="el-icon-user-solid"></el-avatar></div>
<h5 id='name' v-if="contact">{{contact.convUsername}}</h5>
<div id='btnDel'><el-button size="medium" type="danger" icon="el-icon-delete" v-on:click="delContact(contact.convUsername)"></el-button></div>
</el-row>
</div>
</template>
And the data structure is:
data() {
return {
timer: null,
contacts: []
}
And the method of Ajax polling is:
loadContacts () {
var _this = this
console.log('loading contacts')
console.log(localStorage.getItem('username'))
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
console.log('success')
var json = JSON.stringify(resp.data);
_this.contacts = JSON.parse(json);
console.log(json);
console.log(_this.contacts[0].convUserName);
// }
}).catch(failResponse => {
console.log(failResponse)
})
}
This is what I get in the console:
Console Result
And the mounted method I compute is as:
beforeMount() {
var self = this
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
this.$nextTick(() => {
self.contacts = resp.data
})
}).catch(failResponse => {
console.log(failResponse)
})
},
mounted() {
this.timer = setInterval(this.loadContacts(), 1000)
this.$nextTick(function () {
this.loadContacts()
})
},
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
}
I can get the correct data in the console. It seems that the backend can correctly send json to the front, and the front can also receive the right result. But the page just doesn't render as expected.
Any advice would be great! Thank you in advance!

vue-18n - how to force reload in computed function when changing language

I am using vue-i18n but I also have some content which is stored in database. I would like my text to be updated when the user changes the language.
I am using laravel and vuejs2.
Thanks in advance, I am not super familiar with vuejs yet. I hope it's clear enough.
in ContenuComponent.vue
<template>
<div>
{{$i18n.locale}} <== this changes well
<div v-html="textcontent"></div>
<div v-html="textcontent($i18n.locale)"></div> <== this won't work, I am wondering how to put params here (more like a general quetsion)
</div>
</template>
<script>
export default {
name:'contenu',
props: {
content: {
type: String,
default: '<div></div>'
}
},
computed: {
textcontent: function () {
console.log(navigator.language); <== this gives me the language as well, so i could use it if I can make it reload
var parsed = JSON.parse(this.content);
parsed.forEach(element => {
if(navigator.language == element['lang']){
return element['text'];
}
});
}
}
}
</script>
in ContentController
public function getcontent(){
$content = DB::connection('mysql')->select( DB::connection('mysql')->raw("
SELECT text, lang from content
"));
return view('myvue', ['content' => json_encode($content)]);
}
in content.blade.php
<div id="app">
<contenu content="{{ $content }}"></contenu>
</div>
You SHOULD NOT pass parameters to computed props! They are not methods and you should create method instead:
methods: {
textcontent () {
var parsed = JSON.parse(this.content)
parsed.forEach(element => {
if (navigator.language == element['lang']){
return element['text']
}
})
}
}
Also you should consider ES6 syntax:
methods: {
textcontent () {
var parsed = JSON.parse(this.content)
const content = parsed.find(element => navigator.language == element['lang'])
return content['text']
}
}
Much cleaner!
Please make sure to read about computed props and how they are different than methods or watchers: docs

Vue.js Component combined with Laravel Form Validation (i.e. passing an initial value for data)

After much Googling and finding the Vue.js forum down, I am ready to give up.
I'm creating a Postcode Lookup component, and everything was working well until I tried to combine it with Laravel's form validation - particularly when there's an error, and the form re-fills the old values.
Hopefully I cover everything here. I have a form input partial that I use which generates every form input. It also uses Laravel's old(...) value if present.
The issue is because there's a default value (in this case for postcode and address) of an empty string, this overrides the value attribute of Postcode input, and the content of the Address textarea.
In made up land, the ideal would be:
data : function() {
return {
postcode : old('postcode'),
address : old('address'),
addresses : [],
hasResponse : false,
selectedAddress : ''
};
},
So that's what I'm trying to replicate.
I can probably replace validation with Ajax validation, but my form partial changes the appearance of fields with an error slightly, so this would be messy
From my understanding:
I can't set an initial data value, as this will override the input value.
I can set a prop, but this is immutable
Any help I can find suggests 'using a computed property which determines its value from the prop' but if you literally do that, it doesn't update.
Here's what I have so far:
<so-postcode-lookup initial-postcode="{{ old('postcode') }}" initial-address="{{ old('address') }}"></so-postcode-lookup>
/**
* Allow user to select an address from those found in the postcode database
*/
Vue.component('so-postcode-lookup', {
name : 'so-postcode-lookup',
template : '#so-postcode-lookup-template',
props : ['initialPostcode', 'initialAddress'],
data : function() {
return {
postcode : '',
address : '',
addresses : [],
hasResponse : false,
selectedAddress : ''
};
},
computed : {
currentAddress : function() {
if (this.address !== '') {
return this.address;
} else {
return this.initialAddress;
}
},
currentPostcode : function() {
if (this.postcode !== '') {
return this.postcode;
} else {
return this.initialPostcode;
}
},
hasAddresses : function() {
return this.addresses.length;
},
isValidPostcode : function() {
return this.postcode !== '' && this.postcode.length > 4;
},
isInvalidPostcode : function() {
return !this.isValidPostcode;
}
},
methods : {
fetchAddresses : function() {
var resource = this.$resource(lang.ajax.apiPath + '/postcode-lookup{/postcode}');
var $vm = this;
var element = event.currentTarget;
// Fetch addresses from API
resource.get({ postcode : this.postcode }).then(function(response) {
response = response.body;
if (response.status == 'success') {
// Update addresses property, allowing select to be displayed
$vm.addresses = response.data;
} else {
$vm.addresses = [];
}
this.hasResponse = true;
});
},
setAddress : function() {
this.address = this.selectedAddress;
}
}
});
<template id="so-postcode-lookup-template">
<div class="row">
#include('partials.input', [
'label' => trans('register.form.postcode'),
'sub_type' => 'postcode',
'input_id' => 'postcode',
'autocorrect' => false,
'input_attributes' => 'v-model="currentPostcode"',
'suffix_button' => true,
'suffix_button_reactive' => trans('register.form.postcode_button_reactive'),
'suffix_text' => trans('register.form.postcode_button'),
'required' => true,
'columns' => 'col-med-50',
'wrapper' => 'postcode-wrapper'
])
<div class="col-med-50 form__item" v-show="hasResponse">
<label for="address-selector" class="form__label" v-show="hasAddresses">{{ trans('forms.select_address') }}</label>
<select id="address-selector" class="form__select" v-show="hasAddresses" v-model="selectedAddress" #change="setAddress">
<template v-for="address in addresses">
<option :value="address.value">#{{ address.text }}</option>
</template>
</select>
<so-alert type="error" allow-close="false" v-show="!hasAddresses">{{ trans('forms.no_addresses') }}</so-alert>
</div>
#include('partials.input', [
'label' => trans('register.form.address'),
'input_id' => 'address',
'type' => 'textarea',
'input_attributes' => 'v-model="currentAddress"',
'required' => true
])
</div>
</template>
If I try this, and set the model of the inputs to currentPostcode and currentAddress respectively, I seem to get an infinite loop.
I think I'm overthinking this somehow.
You can't bind directly to a prop but you can set an initial value using the prop and then bind to that, which is the way to go if you need a two way binding:
Vue.component('my-input', {
props: {
'init-postcode': {
default: ""
}
},
created() {
// copy postcode to data
this.postcode = this.initPostcode;
},
data() {
return {
postcode: ""
}
},
template: '<span><input type="text" v-model="postcode"> {{ postcode }}</span>'
});
Then just do:
<div id="app">
<my-input init-postcode="{{ old('postcode') }}"></my-input>
</div>
Here's the fiddle: https://jsfiddle.net/vL5nw95x/
If you are just trying to set the initial values, but don't need a two way binding, then you can reference the prop directly - as you won't be applying any changes - using v-bind:value:
Vue.component('my-input', {
props: {
'init-postcode': {
default: ""
}
},
template: '<span><input type="text" :value="initPostcode"> {{ postcode }}</span>'
});
And the markup:
Here's the fiddle: https://jsfiddle.net/pfdgq724/
Im working in a easy way to do that using laravel 5.4 controller to send the data directly
In Laravel view:
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="documento.ciudad" value="{{ old('ciudad', isset($documento->ciudad) ? $documento->ciudad : null) }}" >
in vue.js 2.0
data: {
documento: {
ciudad: $('#ciudad').val(),
},
},
In Laravel Controller
$documento = ReduJornada::where("id_documento",$id)->first();
return view('documentos.redujornada')->with(compact('documento'));

Guess login with firebase and ember

i try to implement a anonymous login with Ember and Firebase. I have successfully configure my project for use with Firebase and Emberfire, and i can login to my Firebase. But when i try to save user information in a Session initializer, i can't retrieve it to make my controllers aware of the user state.
This is my code :
I have a sidebar in my application.hbs that i want to display if the user is connected.
<div class="container-fluid" id="main">
<div class="row">
{{#if loggedIn}}
<aside class="col-xs-3">
{{outlet sidebar}}
</aside>
<div class="col-xs-9">
{{outlet}}
</div>
{{else}}
<div class="col-xs-12">
{{outlet}}
</div>
{{/if}}
</div>
</div>
Inside of my application.js controller i try to define a computed property :
import Ember from "ember";
var ApplicationController = Ember.ObjectController.extend({
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(this.session.get('isConnected')),
});
export default ApplicationController;
this.session references an Initializer that is inject inside of controllers and routes :
import Ember from 'ember';
export function initialize(container, application) {
var session = Ember.Object.extend({
authData : [],
user : null,
login : function(authData, user) {
console.log(authData);
console.log(user);
this.set('authData', authData);
this.set('user',user);
},
getUser: function() {
return this.get('user');
},
getAuthData: function() {
return this.get('authData');
},
isConnected : function() {
return (this.get('user') == null) ? false : true;
}.property('user')
});
application.register('session:main', session, { singleton: true });
// Add `session` object to route to check user
application.inject('route', 'session', 'session:main');
// Add `session` object to controller to visualize in templates
application.inject('controller', 'session', 'session:main');
}
export default {
name: 'session',
initialize: initialize
};
And this is my LoginController :
import Ember from "ember";
var LoginController = Ember.ObjectController.extend({
model : {},
ages : function() {
var ages = Ember.A();
for(var i = 18; i <= 99; i++) {
ages.push(i);
}
return ages;
}.property(),
sexs : ['Male', 'Female'],
actions : {
logIn : function() {
var data = this.getProperties("name", "age", "sex");
var that = this;
this.database.authAnonymously(function(error, authData) {
if (error) {
console.log(error);
} else {
var newUser = that.store.createRecord('user', {
name: data['name'],
age: data['age'],
sex:(data['age'] === "Male" ? 0 : 1)
});
newUser.save();
that.session.login(authData, newUser);
console.log("Toto", that.session.get('isConnected'));
that.transitionToRoute('chat');
}
});
}
}
});
export default LoginController;
So in my application.js, if i define loggedIn to be just a property() not property(this.session.get('isConnected'). loggedIn is not refreshed when the user connects to the application. If i tell it to computes with " this.session.get('isConnected') ", Ember tells me that "this.session" is not defined.
How to refresh this value, to tell to my template to display sidebar if my user is connected?
Simple answer
var ApplicationController = Ember.ObjectController.extend({
loggedIn :Em.computed.alias('session.isConnected'),
// or
loggedIn : function(){
return this.get('session.isConnected');
}.property('session.isConnected')
});
Your problem was your dependencies. Either you weren't watching it (property()) or you were crashing because this.session doesn't exist in the scope of the window. And I doubt Ember was really yelling it at you, more of just the javascript engine while it parsing your javascript.
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(),
// this is resolved while defining the controller, think of its scope
It is resolved like this:
var tmp = this.session.get('isConnected');
var tmp2 = function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(tmp);
var tmp3 = {
loggedIn: tmp2
};
var ApplicationController = Ember.ObjectController.extend(tmp3);

Bootstrap Typeahead with AJAX source (not working)

I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly

Resources