Cakephp Data validation - This field cannot be left blank - cakephp

I'm using cakephp and I get a strange behavior with it.
Here is my validation rule in the Model:
public $validate = array(
'flyer' => array(
'rule' => array('fileValidation', 'flyer', array('image/jpeg', 'image/pjpeg'), NULL, TRUE)
)
// Other rules...
);
Here is the fileValidation method (yes I'm french =) )
public function fileValidation(array $check, $field, array $allowedMimeTypes = NULL, $maxFileSize = NULL, $allowEmpty = FALSE)
{
$file = array_shift($check);
$message = NULL;
if($file['error'] === UPLOAD_ERR_OK){
// checking uploaded file
if(empty($file['tmp_name']) || empty($file['tmp_name']) || $file['tmp_name'] === 'none' || !is_uploaded_file($file['tmp_name'])){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// checking mimeTypes if required
elseif(!empty($allowedMimeTypes) && !in_array($file['type'], $allowedMimeTypes)){
$message = "Le type de fichier envoyé n'est pas celui attendu.";
}
// checking file size if required
elseif(!empty($maxFileSize) && $file['size'] > $maxFileSize){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_NO_FILE){
// validates if no upload is allowed
if(!$allowEmpty){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_INI_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_FORM_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_PARTIAL){
$message = "Une erreur est survenue lors de l'envoi du fichier, le serveur n'a reçu qu'une partie du fichier, veuillez réessayer à nouveau.";
}
elseif($file['error'] >= UPLOAD_ERR_NO_TMP_DIR){
$message = "Une erreur interne est survenue, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// Here is the problem
$this->validationErrors[$field][] = $message;
return FALSE;
}
So far so good, my Validation rule seems to work correctly but when à get an error, I have two messages: "My custom message" and "This file cannot be left blank".
How to remove this message, where am I wrong?
Thanks in advance.

May be it will works for you
$this->validationErrors[$field][] = $message; // comment this Line
return FALSE // comment this Line
And Add the following line at last of your fileValidation function
return implode("\n", $message);

Cakephp.Saint's solution doesn't work because $message is a string, not an array but this works fine:
return $message;

Related

"Cannot read property 'cache' of undefined" when I check a member role

I want to make a mute command for my Discord bot but that create errors:
C:\Program Files\nodejs\node.exe .\index.js
|------ Bot on ------|
index.js:22
Uncaught TypeError: Cannot read property 'cache' of undefined
No debugger available, can not send 'variables'
Process exited with code 1
I want to check if the user who is mentionned has already the mute role and if the executor has an admin role. But that create this error.
My code:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
let User = message.mentions.users.first();
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ let reason = "aucune"}
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time[0]) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
che
if(User.roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
if(!message.author.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
if(User.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time[0] + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
pendant " + time[0] + " secondes pour la raison suivante : " + reason)
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time[0] = 60000
)}
})
Don’t worry about French words.
Your code is not going to do what you want it to do, because you messed up some parts. User will be the first mentioned user that can be found in your arguments. So if you mention the user right at the first position of your arguments, it will be at index 0. That is because the arguments get stored in an array and arrays always starts at index 0. That means now your following arguments have to be at index 1 and 2. So you can change your time and reason into:
let time = message.content.split(" ").slice(1);
let reason = message.content.split(" ").slice(2).join(" ");
Make sure you use .join(" ") at your reason, that will allow you to add multiple words for the reason. The next mistake is in the if-statement where you ask if there is no reason. You create a new variable inside the statement, which makes no sense. You just have to do:
if(!reason){ reason = "aucune"; }
Now if there is no reason provided the reason will be aucune.
If you want to ask if a user has the mute role already, you can use a GuildMember Object. That would look like this:
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
After that if-statement you ask if a user has certain roles and if he don't has this roles, he has no permission. Something like that should always be the first line of code of such a command and it should look like this:
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
The same procedure with the following if-statement:
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
Then in your embed you are using time[0], although time is not an array. It just has to be time.
Your code should look like this now:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
let User = message.mentions.users.first();
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ reason = "aucune"; }
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + message.guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time
)}
})

React-pdf frame proportions

I want to use react-pdf to generate PDF and just followed the exact same steps provided by its official documentation. However when the pdf renders it doesnt occupy the whole screen, and i dont know if im doing sth wrong or there's some property to define that. This is how it looks like:
Code:
import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '#react-pdf/renderer';
import ReactPDF from '#react-pdf/renderer';
// Create styles
// Create Document Component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.body}>
<Text style={styles.header} fixed>
~ Created with react-pdf ~
</Text>
<Text style={styles.title}>Don Quijote de la Mancha</Text>
<Text style={styles.author}>Miguel de Cervantes</Text>
<Text style={styles.subtitle}>
Capítulo I: Que trata de la condición y ejercicio del famoso hidalgo D.
Quijote de la Mancha
</Text>
<Text style={styles.text}>
En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha
mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga
antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que
carnero, salpicón las más noches, duelos y quebrantos los sábados,
lentejas los viernes, algún palomino de añadidura los domingos,
consumían las tres partes de su hacienda. El resto della concluían sayo
de velarte, calzas de velludo para las fiestas con sus pantuflos de lo
mismo, los días de entre semana se honraba con su vellori de lo más
fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina
que no llegaba a los veinte, y un mozo de campo y plaza, que así
ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro
hidalgo con los cincuenta años, era de complexión recia, seco de carnes,
enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que
tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna
diferencia en los autores que deste caso escriben), aunque por
conjeturas verosímiles se deja entender que se llama Quijana; pero esto
importa poco a nuestro cuento; basta que en la narración dél no se salga
un punto de la verdad
</Text>
<Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => (
`${pageNumber} / ${totalPages}`
)} fixed />
</Page>
</Document>
);
App.js
export class App extends Component {
render(){
return (
<PDFViewer>
<MyDocument />
</PDFViewer>
)
}
}
try adding some css styles to your PDFViewer component, in your css file try adding:
.ClassName {
width: 99%;
height: 99vh;
}

ZAPIER CODE STEP HTTP REQUEST

I need generate the following request in zapier with a code step. I use webhook function but for some reason the answer is a separated comma value and i need the full json. I try in postman and works perfect. But i dont unterstand so fine how i can do with code. I use postman to format the code in nodejs the code run but dont geck back anything. Somebody can help so fin the problem? thans so much. (i´m a basic user for that reason i dont untersant all)
The request:
curl -X POST \
'https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=true' \
-H 'accept: application/json' \
-H 'accept-language: es' \
-H 'authorization: Basic here is the token' \
-H 'cache-control: no-cache' \
var http = require("https");
var options = {
"method": "POST",
"hostname": "gateway.watsonplatform.net",
"port": null,
"path": "/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=false",
"headers": {
"content-type": "application/json",
"accept": "application/json",
"authorization": "Basic HEREISTHETOKEN==",
"accept-language": "es",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ contentItems:
[ { content: 'Wow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClass So great! #MasterClasWow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClasss',
contenttype: 'text/plain',
created: 1447639154000,
id: '666073008692314113',
language: 'es' } ] }));
req.end();
return {DATA: http.text};

Datatables change interface language

I am currently using angular-datatables.
How can I see the interface of the table in other languages?
I mean the "Show entries", "Search:", "Showing 1 to 10 of 20 entries" literals fore example in Spanish.
You need to define a language struct like this (danish implementation, what I am using in my angular-datatables apps) :
var language = {
"sEmptyTable": "Ingen tilgængelige data (prøv en anden søgning)",
"sInfo": "Viser _START_ til _END_ af _TOTAL_ rækker",
"sInfoEmpty": "Viser 0 til 0 af 0 rækker",
"sInfoFiltered": "(filtreret ud af _MAX_ rækker ialt)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Vis _MENU_ rækker",
"sLoadingRecords": "Henter data...",
"sProcessing": "Processing...",
"sSearch": "Filter:",
"sZeroRecords": "Ingen rækker matchede filter",
"oPaginate": {
"sFirst": "Første",
"sLast": "Sidste",
"sNext": "Næste",
"sPrevious": "Forrige"
},
"oAria": {
"sSortAscending": ": activate to sort column ascending",
"sSortDescending": ": activate to sort column descending"
}
}
There is a bunch of languages here -> https://www.datatables.net/plug-ins/i18n/
And then you include the language using the withLanguage() option method
.withLanguage(language)
demo -> http://plnkr.co/edit/RCrqM3z7qwsUfFwy8HE6?p=preview
I created a .ts file like this:
export class LanguageApp {
public static spanish_datatables = {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ &elementos",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
}
Then in the component that was loading the DataTable just put that config inside dtOptions:
this.dtOptions = {
language: LanguageApp.spanish_datatables
};
In Angular2+ what worked for me is quite the same as mentioned by #davidkonrad, but without the starting letters (s and o), and adding the language as an attribute of the dtOptions. I.e.:
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
dom: 'Bfrtip',
buttons: [
/*'print',
'csv'*/
],
responsive: true,
/* below is the relevant part, e.g. translated to spanish */
language: {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ éléments",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
};

What is wrong when I call this array from a variable?

I have been do it a template page for Wordpress Theme. In it, have to filter some tags from an user field.
But for test, I do it that:
$user_id = get_current_user_id();
$contexto = get_user_meta($user_id, 'contexto', true);
$contexto = '"' . $contexto . '"';
$array = array (
"Buscando mi nicho​" => "buscando-mi-nicho",
"Montando mi blog" => "montando-mi-plataforma",
"Buscando lectores" => "buscando-lectores",
"Construyendo mi lista de correo​" => "construyendo-mi-lista-de-correo",
"Vendiendo mi primer producto/servicio​" => "vendiendo-mi-primer-productoservicio",
"Buscando más clientes​​​" => "escalar-ventas",
"A punto de dar el gran salto (para vivir de mi blog)​" => "a-punto-de-dar-el-gran-salto-para-vivir-de-mi-blog",
"Ya soy Knowmada Full Time​" => "ya-soy-knowmada-full-time"
);
$etiqueta = $array[$contexto];
$user_first = get_user_meta( $user_id, 'first_name', true );
echo '<p>Hola '. $user_first . '. Queremos ayudarte a progresar, y tu etapa actual es <strong>' . $contexto . '</strong>, por eso, te recomendamos los siguientes contenidos con la etiqueta <b>' . $etiqueta . '</b></p>';
And I get:
Hola Javier. Queremos ayudarte a progresar, y tu etapa actual es "Montando mi blog", por eso, te recomendamos los siguientes contenidos con la etiqueta
You can see, that I don't get the variable $etiqueta.
If I put, for example:
$etiqueta = $array["Montando mi blog"];
I get:
Hola Javier. Queremos ayudarte a progresar, y tu etapa actual es "Montando mi blog", por eso, te recomendamos los siguientes contenidos con la etiqueta montando-mi-plataforma
So I get $etiqueta.
What is wrong whit:
$etiqueta = $array[$contexto];
It is because the keys in your array to not have the double quotes ("). Remove the line:
$contexto = '"' . $contexto . '"';
and it should work.

Resources