I have a modal with a single select called "Impacto OEE" that has 3 options "Queda de Disponibilidade", "Queda de Performance" and "Nenhum". If the option chosen by the user is "Queda de Disponibilidade" it will be saved as "Disponibilidade", if it is "Queda de Performance" it will be "Performance" and if it is "Nenhum" it will be "Nenhum". But when I click on register it is only saved as "Disponibilidade" or "Nenhum". In my database (PostgreSQL) the column is called "impact_oee" as ENUM with values "Disponibilidade, "Performance", "Nenhum".
I'm new to Angular, but I don't understand what I should do to make it work correctly, or what am I doing wrong. Below are parts of the code. Can someone help me?
Here is my code in HTML:
<div class="input-group">
<isteven-multi-select directive-id="impactos" tabindex="4" class="multiselect" helper-elements="filter"
translation="traducaoMultiSelect"
input-model="impactos"
output-model="impacto"
button-label="name"
item-label="name"
tick-property="ticked"
ng-class="{'open':impactosOpen }"
on-open="impactosOpen = true"
on-close="impactosOpen = false"
selection-mode="single" />
</div>
MultiSelect Config:
$scope.impactos = [{ name: "Queda de Disponibilidade" }, { name: "Queda de Performance" }, { name: "Nenhum" }]
Where do I get the data from my server:
new Promise(function (resolve, reject) {
restApi.motivosParadaGerenciamento.query({}, function (array) {
$scope.motivos = [];
if (array.length > 0) {
for (var i = 0; i < array.length; i++) {
$scope.motivos.push({
id: array[i].id,
...
impactos: array[i].impacto_oee,
...
});
}
}
My register function:
function cadastrar () {
restApi.gerenciamentoMotivosParada.save({
...
impacto_oee: $scope.selectedUnique($scope.impactos) === "Queda de Disponibilidade" ? "Disponibilidade" : "Queda de Performance" ? "Performance" : "Nenhum",
}, ...
}
I have an update function that is used in the editing part that also doesn't work when I select "Nenhum". The "Nenhum" option is simply ignored.
function atualizar () {
var motivo;
if ($scope.editing >= 0) {
motivo = {
...
impacto_oee: $scope.selectedUnique($scope.impacto) === "Queda de Disponibilidade" ? "Disponibilidade" : "Queda de Performance" ? "Performance" : "Nenhum" ? "Nenhum" : "Nenhum"
...
};
}
Issue is in your register function. Correct way to write it is as follows
function cadastrar () {
restApi.gerenciamentoMotivosParada.save({
...
impacto_oee: ($scope.selectedUnique($scope.impactos) === "Queda de Disponibilidade") ? "Disponibilidade" : ($scope.selectedUnique($scope.impactos) === "Queda de Performance") ? "Performance" : "Nenhum",
},
...
}
Explanation:
Basically what you are trying to achieve using Ternary Operator is if-elseif-else
if (condition1) {
//value1
} else if(condition2) {
//value2
} else {
//value3
}
in your case, condition2 was missing, that is the reason, it was not checking "Queda de Performance" condition
Related
I have a problem with reseting fields of my form.
I have a form. The user can adding another forms and another ...
If everything is OK, I would like to recording data in my DB and in my store AND reset all of inputs of my form. This is this last point I cannot do.
I have tried different solutions but It does not work.
This is my code :
<div v-for="(question, index) in questionsSignaletiques" :key="index" class="blockQuestion" >
<!--form to add questions : one form per question, each form have a different name in the ref -->
<a-form-model
layout="inline"
:ref="'p' + index"
>
<p>New question</p>
<a-alert v-if="question.error.here" type="error" :message="question.error.message" show-icon />
<a-form-model-item>
<a-input v-model="question.question.type" placeholder="Title">
</a-input>
</a-form-model-item>
<a-form-model-item>
<a-input v-model="question.question.item" placeholder="Item">
</a-input>
</a-form-model-item>
<br><br>
<a-form-model-item label="Question multiple" prop="delivery">
<a-switch v-model="question.question.multiple" />
</a-form-model-item>
<a-form-model-item label="Obligatoire" prop="delivery">
<a-switch v-model="question.question.obligatoire" />
</a-form-model-item>
<br><br>
<div class="blockChoices">
<div v-for="subrow in question.question.choices">
<a-form-model-item>
<a-input v-model="subrow.name" placeholder="Choix">
</a-input>
</a-form-model-item>
</div>
</div>
<a-button #click="addChoice(question)" type="secondary">Add a choice</a-button>
</a-form-model>
</div>
<div>
<a-button #click="addItem" type="secondary">Add a question</a-button>
</div>
<br>
<div>
<a-button #click="submit" type="primary">Send</a-button>
</div>
Javascript code :
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
],
}
},
mounted() {
//retreive all the questions still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
//on met les données dans le store
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//Adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// Sending the forms
submit () {
//loop table to retrieve all questions and indexes if the user adding several questions
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
//loop on choices to see if empty one or not
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; // stop here if error
}
else
{}
}// end loop of choices
// verify other fields
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "Title and item must not be empty"
}
else
{
// everything is ok we can record in db and store
//reset fields == does not work
this.$refs['p' + index][0].fields.resetField()
//this.$refs['p' + index][0].resetFields();
// adding questions in db one by one
/*
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
console.log(result)
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
*/
}
}) //end loop foreach
}
}
};
Thanks a lot for help
EDIT AFTER THE FIRST ANSWER
Ok I didn't know. So I changed my mind : I added a "show" in my "data" which is true at the beginning. If everything is ok, I save the question and set the show to false.
The problem now is that when I have a question that is OK and the other one that is not. When I correct the question that was not ok and save it, BOTH questions go into the STATE. So there is a duplicate in my state AND my DB... What can I do? This is the code :
I just added this in the HTML :
<div v-for="(question, index) in questionsSignaletiques" :key="index" >
<a-form-model
layout="inline"
v-if="question.show"
class="blockQuestion"
>
...
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true,
}
],
}
},
mounted() {
//retrieve question still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// submit the form
submit () {
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; //on s'arrête là si il y a une erreur
}
else
{
console.log("no problem")
}
}
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "You must fill type and item"
}
else
{
// hide the question form
element.show =false
//adding in db
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
}
}) //end loop foreach
}
}
};
Thanks for help !
form.reset() does not work when using v-model.
Reset the reactive data instead.
reset() {
this.question.question.type = ""
...
...
}
My ionic app fires a modal twice when hitting ion-button.
I cannot figured why it is happening.
<ion-button (click)="editProduct(p.id)" fill="clear">
<ion-icon name="cloud-upload"></ion-icon>
</ion-button>
editProduct(id) {
// obter dados do produto pelo seu id
this.afs.collection("products").doc(id)
.valueChanges()
.subscribe(data => {
this.product = data
// chamar o modal e enviar o id do produto
this.modalProduct(id);
});
}
async modalProduct(id) {
const modal = await this.modalCtrl.create({
component: AdminProductPage,
componentProps: {
'id': id,
'title': this.product.title,
'description': this.product.description,
'price': this.product.price,
'image': this.product.image
}
});
await modal.present();
}
I figured out by myself.
I need to use a pipe from rxjs to prevent double execution of editProduct() subscrive method.
editProduct(id) {
// obter dados do produto pelo seu id
this.afs.collection("products").doc(id)
.valueChanges()
.pipe(
first()
)
.subscribe(data => {
this.product = data
// chamar o modal e enviar o id do produto
this.modalProduct(id);
});
}
I'm new to symfony, I render forms throughout a JSON so whenever I click on an icon it shows different forms (to change firstname, lastname...).
I return thoses forms as a JSON :
public function profileSettings()
{
$user = $this->getUser();
// Formulaire d'informations concernant le compte
$formAccountSettings = $this->createForm(AccountSettingsType::class, $user, [
'userEmail' => $user->getEmail(),
'userUsername' => $user->getUsername(),
]);
// Formulaire d'informations personnel
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user, [
'userFirstname' => $user->getFirstname(),
'userLastname' => $user->getLastname(),
]);
// Retour en format JSON des 3 requêtes sous tableau
return $this->json(
[
'formAccountSettingsView' =>
$this->render('user/_accountSettings.html.twig', [
'form' => $formAccountSettings->createView(),
]),
'currentUser' => $user,
'formPersonnalSettingsView' => $this->render('user/_accountSettings.html.twig', [
'form' => $formPersonnalSettings->createView(),
]),
]
);
}
Here is how I display this :
$('#settings-user li').on('click', function (e) {
$.ajax({
type: 'GET',
url: "/website-skeleton/public/index.php/json/profile",
success: function (response) {
if ($(e.target).hasClass('profile')) {
$('.display').empty().append(
`
<p id="welcome">Bonjour, <em><strong>${response['currentUser']['username']}</strong></em> vous êtes enregistré sous le nom de <strong>${response['currentUser']['firstname']} ${response['currentUser']['lastname']}</strong>.
<br>
Votre adresse email est : <strong>${response['currentUser']['email']}</strong>.
<br>
Pour modifiez vos informations veuillez cliquez sur le menu de navigation.
</p>`);
} else if ($(e.target).hasClass('security')) {
$('.display').empty().append(response['formAccountSettingsView']['content']);
} else if ($(e.target).hasClass('informations')) {
$('.display').empty().append(response['formPersonnalSettingsView']['content'])
}
}
})
});
The problem now is that I don't know how to handle thoses forms from another controller and validate it with the constraints I set on my entity User this is how I validate :
public function editCredentials(Request $request, UserPasswordEncoderInterface $encoder)
{
$user = $this->getUser();
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user);
if ($request->isMethod('POST')) {
if ($request->request->has('personnal_settings')) {
if ($formPersonnalSettings->isSubmitted() && $formPersonnalSettings->isValid()) {
$user->setFirstname($request->request->get('personnal_settings')['firstname']);
$user->setLastname($request->request->get('personnal_settings')['lastname']);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('personnal_success', 'Vos informations personnels ont bien été enregistrées !');
return $this->redirectToRoute('user_profile');
}
}
Is that a good method? should I handle everything with ajax ? Thanks for your time !
You should use the handlerequest which automatically sets the values in the form to the entity added to it once the form has been submitted.
$form = $this->createCreateForm($entity); // private function to create the form
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
}
}
return $response;
Once handled you just need to return an ok response, or return the form back to the view if something has gone wrong.
If I remember well, the asserts set on the entity are also automatically processed with the handleRequest(), it depends on how you declared them.
Yo can also add other errors after the submit, just add them between the isSumbmitted() and isValid(). Documentation
I leave you here some documentation that may help.
Handle request
Validation
Validation in the form itself
hi guys i am working on forget password in mobile app using nativescript, and i want to show alert message when the user insert wrong email or wrong apssword in the dialog , but i couldn't make it is there any body can help ?
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass: PromptResult) => {
if (pass.text && pass.result == true) {
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe de nouveau",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass2: PromptResult) => {
if (pass2.text && pass2.result == true) {
if (pass.text == pass2.text) {
this.auth.resetMDP(this.email, this.code, pass2)
.then((res: any) => {
if (res.message == 'OK')
alert('votre mot de passe a été changé avec succès')
}).catch((err: any) => { alert(err); })
} else alert("re-entrez le mot de passe correctement s'il vous plait");
}
})
}
});
because i ve tried to make it work , but the dialog always close
In my apps I use modals to handle custom dialog styling and special action (as you require validation without closing the dialog). The easiest is:
This is how you call it:
page.showModal(
"you/path/to/modal/directory",
{
// your binding context
},
() => {
// on close callback
}
);
Assume that you have modal layout as XML and code behind (in my case Typescript):
<Page xmlns:RL="nativescript-ripple" xmlns="http://schemas.nativescript.org/tns.xsd" shownModally="onShownModally" >
<DockLayout stretchLastChild="false">
<Label dock="top" text="Hello Modal!!" horizontalAlignment="center" />
<TextView dock="top" text="{{ message }}" fontSize="15sp" horizontalAlignment="left" />
<Button dock="bottom" text="OK" tap="onOkTap" />
</DockLayout>
let closeCallback: () => void;
export function onShownModally(args: any) {
const page: Page = <Page>args.object;
const context = args.context;
// your close callback logic that you passed
closeCallback = args.closeCallback;
// bind you context object to modal
page.bindingContext = fromObject(context);
}
export function onOkTap(args: EventData) {
const page = args.object as Page;
if (closeCallback !== null && closeCallback !== undefined) {
closeCallback();
} else {
page.closeModal();
}
}
I'm using the below JS to feed options for my select:
//**** Instance des Bootstrap-SelectPicker ****
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4,
showSubtext: true,
noneSelectedText: 'Pas de sélection',
showSubtext: true,
showTick: true,
});
var menus = [
{ controleur: "CatDdeurs", element: "Cat_Ddeur" },
{ controleur: "Communautes", element: "Communaute" },
{ controleur: "Occupations", element: "Occupation" },
{ controleur: "Provinces", element: "Province" },
{ controleur: "Scolarites", element: "Scolarite" },
{ controleur: "Sexes", element: "Sexe" },
{ controleur: "Situations_Matrimoniales", element: "SituationMatrimoniale" },
{ controleur: "Source_De_Revenus", element: "SrceRevenu" },
{ controleur: "Statuts_Legaux", element: "StatutLegal" },
{ controleur: "Tranche_Revenu", element: "TrancheRevenu" },
{ controleur: "Villes", element: "Ville" },
{ controleur: "Sources_Informations", element: "SceInfo" },
{ controleur: "Langues", element: "langMaternelle" },
{ controleur: "Langues", element: "LangAutre" },
{ controleur: "Conseillers", element: "Conseiller" },
];
menus.forEach(x => {
MenusDeroulants('GetListe' + x.controleur, $('#cbx_' + x.element));
});
//**** Permet de remplir la liste des menus déroulants ****
function MenusDeroulants(url, dropdown) {
$.getJSON(url, function (data) {
dropdown.empty();
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var prenom;
var nom;
var ID;
//**** Traitement des demandeurs ou conseillers ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
//**** Retrait du code ****
if (key == 'Code_Conseiller' || key == 'Code_Demandeur') {
ID = obj[key];
};
//**** Retrait du Nom ****
if (key == 'Nom_Conseiller' || key == 'Nom_Demandeur') {
//if (key.match(/Nom_C*/) || key.match(/Nom_D*/)) {
nom = obj[key];
};
//**** Retrait du Prénom ****
if (key == 'Prenoms_Conseiller' || key == 'Prenoms_Demandeur') {
prenom = obj[key];
};
} else { //**** Traitement des autres menus ****
//**** Retrait de l'ID ****
if (key.match(/ID_*/)) {//**** Traitement des demandeurs ou conseillers ****
ID = obj[key];
};
//**** Retrait du Nom ****
if (key.match(/Nom_*/)) {
nom = obj[key];
};
};
}
//**** On construit les options du menu déroulant ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
dropdown.append($("<option></option>").attr("value", ID).text(nom).attr("data-subtext", prenom));
} else {
dropdown.append($("<option></option>").attr("value", ID).text(nom));
};
if ((nom.toUpperCase() == "CHICOUTIMI" && url == 'GetListeVilles')
|| (nom.toUpperCase() == "QUÉBEC" && url == 'GetListeProvinces')
|| (nom.toUpperCase() == "NON DISPONIBLE" && url != 'GetListeVilles' && url != 'GetListeProvinces')) {
dropdown.prop("selectedIndex", i);
};
}
dropdown.selectpicker('refresh');
});
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<td style="padding-left:10px">
<div class="form-group">
<label for="cbx_Sexe" class="control-label">Sexe:</label>
<div>
<select class="selectpicker" id="cbx_Sexe"></select>
</div>
</div>
</td>
The first 12 elements will work fine but as soon as I add the 3 last, my selects will start behaving funny: The 3 lasts will sometimes work fine and some times show a white space on top of the box.
Sometimes, menus will not close when I open others... and so on.
I have tried combining the 12 first with each of the 3 lasts but there will always be something.
More strange is that if I use let say : "{ controleur: "Sexes", element: "Sexe" }," to fill all 3 that are giving me issue, all works perfectly.
Below is a screenshot of the display I'm getting:
Changing my function (MenusDeroulants) parameter dropdown to $dropdown finally solved the issue.