How to keep dialogs showed up and alert nativescript - javascript

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();
}
}

Related

Error in vue js, problems with v-show or v-if

Good morning people, I'm going to comment on my mistake. This is a users screen. Where I have a record and an edit. Register is with id 0 and edit i have id types. My idea was, when you enter the registrar, you will see the change password fields (so far everything is perfect.). The issue is on the edit screen, my idea is until I select the role, the password fields did not appear. Once you choose the role, you can change your password.
Then I have the select, of roles. That the idea would be to bring me the role. And it doesn't. It takes me the text-field, but in the v-select it doesn't bring me the value. Attached images below.
v-select error does not bring me the data.
The roles are shown to me, but I would like it to be put in the select, as in the text fields. is there any way?
And there once the role is selected. The idea would be that the password fields appear. If there is no role selected, it should not appear.
<v-form ref="form" lazy-validation>
<v-select
label="Rol"
v-model="form.rolId"
:items="roles"
item-value="value"
item-text="text"
:rules="[(v) => !!v || 'Este campo es requiredo']"
required
></v-select>
<v-text-field
v-model="form.password"
v-show="showPassword"
:rules="[(v) => !!v || 'Este campo es requiredo']"
:type="'password'"
label="Contraseña"
required
></v-text-field>
<v-text-field
v-model="form.confirmPassword"
v-show="showPassword"
:rules="[(v) => !!v || 'Este campo es requiredo']"
:type="'password'"
label="Confirmar contraseña"
required
></v-text-field>
<v-row class="text-center">
<v-col cols="12" lg="3">
<v-btn
block
class="mr-4 blue white--text rounded-lg"
#click="submit"
submit
>Guardar</v-btn
>
</v-col>
</v-row>
</v-form>
data() {
return {
form: {},
showPassword: true,
roles: [
{ value: "Agente", text: "Agente" },
{ value: "Administrador", text: "Administrador" },
],
};
},
getOne(id) {
if (id != "0") {
this.showPassword = false;
this.usuarioServices
.getOne(id)
.then((data) => {
this.form = data;
this.form.password = "Encripted";
this.form.confirmPassword = "Encripted";
})
.catch((error) => {
console.log(error.response.status);
});
}
},
submit() {
if (this.form.password != this.form.confirmPassword) {
this.showError("Las contraseñas no coinciden.");
return;
}
this.$refs.form.validate();
if (this.$refs.form.validate(true)) {
Swal.fire({
title: "Espere unos momentos ...",
showConfirmButton: false,
});
if (this.form.id == "0") {
this.usuarioServices
.registrar(this.form)
.then((data) => {
Swal.close();
if (data == "") {
this.$router.push({ path: "/usuarios/listar" });
this.showSuccess("Entro al sistema correctamente.");
}
})
.catch((error) => {
Swal.close();
if (error.response.status == 401) {
this.showError("El mail o password es invalido.");
} else {
this.showError(error.response.data);
}
console.log(error.response.status);
});
} else {
this.usuarioServices
.editar(this.form)
.then((data) => {
Swal.close();
if (data == "") {
this.$router.push({ path: "/usuarios/listar" });
this.showSuccess("Entro al sistema correctamente.");
}
})
.catch((error) => {
Swal.close();
if (error.response.status == 401) {
this.showError("El mail o password es invalido.");
} else {
this.showError(error.response.data);
}
console.log(error.response.status);
});
}
}
},
As mentioned, you are facing two challenges in your code :
1. How to hide/show password text fields based on the role select by the user ?
Instead of v-show="showPassword", You can simply do v-show="form.rolId" in both the password text fields. As form.rolld is containing the selected role value. Hence, if it will be falsy (empty/null/undefined) .. text fields will not be shown.
2. How to display/show existing role (which coming from database) in the select box when user is on edit page ?
I can see, API returning roles as an array ['Agente']. Hence, while binding the value to v-model in the <v-select>. It should be access via zero index apiResponse.roles[0].

How can I save a option from multi select in Angular?

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

Ionic modal fires twice

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);
});
}

Symfony form validation from an AJAX render

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

How to read a JSX component inside a javascript code

I have this delete function :
showDeleteConfirmation(value, id, index, thisHandler) {
//const { extraitMP3 } = this.state;
confirm({
title: 'Voulez vous supprimer cette audio ?',
content: '',
okText: 'Oui, je confirme',
okType: 'danger',
cancelText: 'Non',
onOk() {
deleteMp3Request(id);
var { extraitMP3 } = thisHandler.state;
var array = [];
for (var key in extraitMP3) {
array.push(extraitMP3[key]);
}
// console.log('array',array)
const result = array.map(d => ({
...d,
TypeMp3List:
Object.fromEntries(
//console.log(Object.entries(d.TypeMp3List)),
Object.entries(d.TypeMp3List).splice(index,id)
)
}))
// console.log('result',result)
thisHandler.setState({ extraitMP3: result })
NotificationManager.success("le fichier audio est supprimé avec succès !", "");
},
onCancel() {
},
});
}
I want to replace the text messages with :
title: <IntlMessages id="message.required.titresuppressionmp3" />,
content: '',
okText: <IntlMessages id="message.required.confirmation" />,
okType: <IntlMessages id="message.required.danger" />,
cancelText: <IntlMessages id="message.required.non"/>,
I did the import but it's not working correctly What should I do exactly to be read successfully. Any help would be appreciated. Thank you
The browsers doesn't support JSX, so you must use babel to convert the JSX into understandable for the browser javascript code. Check this tutorial

Categories