anybody please give an example of validation form in cakephp, because i have cakephp 2.3.3 and cant' validate forms, doesnt recognize my model Usuario
model usuario
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
};
public $validate = array(
'nombre' => array(
'sololetras' =>array(
'rule' => '/^[a-z]$/i',
'message' => 'Solo se Permite Letras en este Campo'
),
'required'=> true,
'allowEmpty' => false,
),
'apellido' => array(
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'El nombre de usuario debe ser una dirección de email válida.'
),
'allowEmpty' => false,
'required' => true,
),
'nrotlf' => array(
'rule' => array('phone', null, 'us')
)
);
}
?>
UsuarioController
<?php
class UsuariosController extends AppController{
var $name = 'Usuarios';
var $helpers = array('Html','Form');
//var $scaffold;
function cargapaq(){ //Carga la lista de la tabla Paquete
$this->loadModel('Paquete');
$paquetes = $this->Paquete->find('list', array('fields'=>'Paquete.id, Paquete.nombre'));
//debug($paquetes);
$this->set(compact('paquetes'));
}
function cargamod(){ //Carga la lista de la tabla Modelo
$this->loadModel('Modelo');
$modelos = $this->Modelo->find('list', array('fields'=>'Modelo.id, Modelo.nombre'));
//debug($modelos);
$this->set(compact('modelos'));
}
function index(){
$usuarios = $this->Usuario->find('all',array(
'fields'=>array(
'Usuario.nombre',
'Usuario.apellido',
'Usuario.email',
'Usuario.password',
'Usuario.grupo_id',
'Usuario.paquete_id',
'Usuario.modelo_id',
'Usuario.nrotlf',
'Usuario.valido',
'Usuario.id'),
'conditions'=>'Usuario.valido=true',
'order'=>'Usuario.apellido ASC')
);
$this->set('usuarios',$usuarios);
###Carga del nombre de los modelos de telefonos para cada modelo en el index.ctp####
$idmod = Hash::extract($usuarios,'{n}.Usuario.modelo_id');
$array=array();
$modelos=array();
$this->loadModel('Modelo');
for ($i=0; $i < count($idmod); $i++) {
$busqueda = $this->Modelo->find('all', array('fields'=>'Modelo.nombre', 'conditions'=>"Modelo.id=$idmod[$i]"));
array_push($modelos, $busqueda['0']);
}
$this->set('modelos',$modelos);
#######Fin de La Carga#########
###Carga del nombre de los planes de telefonos para cada modelo en el index.ctp####
$idpaq = Hash::extract($usuarios,'{n}.Usuario.paquete_id');
$array=array();
$paquetes=array();
$this->loadModel('Paquete');
for ($i=0; $i < count($idpaq); $i++) {
$busqueda = $this->Paquete->find('all', array('fields'=>'Paquete.nombre', 'conditions'=>"Paquete.id=$idpaq[$i]"));
array_push($paquetes, $busqueda['0']);
}
$this->set('paquetes',$paquetes);
#######Fin de La Carga#########
}
function add(){
if ($this->request->is('post')){
//$this->Usuario->create();
if ($this->Usuario->save($this->request->data)){
$this->Session->SetFlash('Usuario Nuevo Creado');
$this->redirect(array('action'=>'index'),null,true);
}else{
$this->Session->SetFlash('No se ha Agregado el Usuario, intente de Nuevo');
}
}
$this->cargapaq();
$this->cargamod();
}
add.ctp
<?php echo $this->Form->create('Usuario');?>
<fieldset>
<legend>Añadir Nuevo Usuario</legend>
<?php
echo $this->Form->input('nombre');
echo $this->Form->input('apellido');
echo $this->Form->input('email',array('label'=>'Correo Electrónico'));
echo $this->Form->input('password',array('label'=>'Contraseña'));
echo $this->Form->input('password2',array('label'=>'Repita Contraseña', 'type'=>'password'));
echo $this->Form->input('paquete_id',array('label'=>'Plan','empty'=>'(Seleccione un Plan)'));
echo $this->Form->input('modelo_id',array('label'=>'Modelo de Teléfono','empty'=>'(Seleccione un Modelo)'));
echo $this->Form->input('nrotlf',array('label'=>'Numero de Teléfono'));
echo $this->Form->input('grupo_id',array('empty'=>'(Seleccione un Rol)'));
echo $this->Form->input('valido', array('checked'=>'true'));
?>
</fieldset>
<?php echo $this->Form->end('Enviar') ?>
<?php echo $this->Html->link('Mostrar Todos Los Usuarios',array('action'=>'index')); ?>
i've seen the documentation but i can make the validation work
I solved the problem.. was the name of the model and doesnt recongnize the validation
Related
In my HunterModel.php file all the validations and custom messages are from the validations, but I don't know if my form_create.php doesn't show the error messages, they simply return to the form without shows the failures committed by the user, why is this happening?
form_create.php
<?php if (isset($validation)) : ?>
<div class="text-danger">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>
<form action="<?= site_url('create')?>" method="POST">
...
</form>
In my HunterController.php method createHunter() must do the record insertion operation, checking if everything is right or returns to the form showing the necessary corrections to the user.
HunterController.php
public function createHunter()
{
try {
helper(['form']);
$hunter = new HunterModel();
$data = [
'name_hunter' => $this->request->getPost('name_hunter'),
'age_hunter' => $this->request->getPost('age_hunter'),
'height_hunter' => $this->request->getPost('height_hunter'),
'weight_hunter' => $this->request->getPost('weight_hunter'),
'type_hunter' => $this->request->getPost('type_hunter'),
'type_nen' => $this->request->getPost('type_nen'),
'type_blood' => $this->request->getPost('type_blood')
];
if ($hunter->insert($data)){
return $this->response->redirect(site_url('listing'));
} else {
$data['validation'] = $this->validator;
echo view('form_create', $data);
}
} catch (\Exception $e) {
exit($e->getMessage());
}
}
HunterModel.php
// Validation
protected $validationRules = [
'nome_hunter' => 'required|max_length[30]',
'idade_hunter' => 'required|integer',
'altura_hunter' => 'required|decimal',
'peso_hunter' => 'required|decimal',
'tipo_hunter' => 'required|max_length[30]',
'tipo_nen' => 'required|max_length[30]',
'tipo_sanguineo' => 'required|max_length[3]'
];
protected $validationMessages = [
'nome_hunter' => [
'required' => 'O nome do Hunter não pode ficar vazio.',
'max_length' => 'O nome do Hunter precisa ter no máximo 30 caracteres.'
],
'idade_hunter' => [
'required' => 'A idade do Hunter não pode ficar vazia.',
'integer' => 'A idade do Hunter precisa ser um número inteiro.'
],
'peso_hunter' => [
'required' => 'O peso do Hunter não pode ficar vazio.',
'decimal' => 'O peso do Hunter precisa ser um número decimal.'
],
'altura_hunter' => [
'required' => 'A altura do Hunter não pode ficar vazia.',
'decimal' => 'A altura do Hunter precisa ser um número decimal.'
],
'tipo_hunter' => [
'required' => 'É necessário definir o tipo de Hunter.',
'max_length' => 'O tipo de Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_nen' => [
'required' => 'É necessário definir o nen do Hunter.',
'max_length' => 'O nen do Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_sanguineo' => [
'required' => 'É necessário definir o tipo sanguíneo do Hunter.',
'max_length' => 'O tipo sanguíneo do Hunter precisa ter no máximo 3 caracteres.'
]
];
you should learning again about validate data,
learn this page
https://codeigniter4.github.io/userguide/libraries/validation.html#form-validation-tutorial
if you want to use helper function, try this
function yourController($request){
helper(['form']);
$validation = \Config\Services::validation();
$rules = [
"nome_hunter" => [
"label" => "nome_hunter",
"rules" => 'required|max_length[30]',
]
];
if ($this->validate($rules)) {
$hunter = new HunterModel();
$hunter->insert($data)
$session = session();
$session->setFlashData("success", "Successful");
return redirect()->to('/');
} else {
$data["validation"] = $validation->getErrors();
}
}
or you can make the validation on your controller, don't make it on model
you can try this too
how to validate form data in codeigniter 4
Why is my validator is not validating the input-email field, it accepts anything!
This is my controller to update the database. The name in form is correct
Edit: This is my entire code, I post here my code with just email but one guy said that is working, so why this is not working with my entire code of update database?
public function atualizar(Request $req)
{
$erros = [
'input-nome.max' => 'Introduziu carateres acima do máximo no campo do nome!',
'input-facebook.max' => 'Introduziu carateres acima do máximo no campo do facebook!',
'input-instagram.max' => 'Introduziu carateres acima do máximo no campo do instagram!',
'input-descricao.max' => 'Introduziu carateres acima do máximo no campo da descrição!',
'input-profissao.max' => 'Introduziu carateres acima do máximo no campo da profissão!',
'input-imagem.max' => 'O tamanho máximo do ficheiro é de 10mb!',
'image' => 'O ficheiro que inseriu não é imagem!',
'mimes' => 'A extensão da imagem não é permitida, apenas JPEG, JPG e PNG!',
'email' => 'Introduza um e-mail válido!'
];
$validator = Validator::make($req->all(), [
'input-nome' => 'max:25',
'input-email' => 'nullable|required_with:input-email|email:rfc,dns,filter',
'input-facebook' => 'max:40',
'input-instagram' => 'max:40',
'input-profissao' => 'max:25',
'input-descricao' => 'max:120',
'input-imagem' => 'image|mimes:jpeg,png,jpg|max:10240'
], $erros);
$id = $req->input('input-id');
$membrosEquipa = DB::table('equipa')
->where('id', $id)
->get();
$inputEmail = $req->input('input-email');
if (!isset($inputEmail)) {
$inputEmail = null;
}
if ($req->filled('input-email')) {
$inputEmail = $req->input('input-email');
}
$inputNome = $req->input('input-nome');
$inputFacebook = $req->input('input-facebook');
$inputInstagram = $req->input('input-instagram');
$inputProfissao = $req->input('input-profissao');
$inputDescricao = $req->input('input-descricao');
$inputImagem = $req->file('input-imagem');
foreach ($membrosEquipa as $membro) {
if (!isset($inputNome)) {
$inputNome = $membro->nome;
}
if (!isset($inputFacebook)) {
$inputFacebook = $membro->facebook;
}
if (!isset($inputInstagram)) {
$inputInstagram = $membro->instagram;
}
if (!isset($inputProfissao)) {
$inputProfissao = $membro->profissao;
}
if (!isset($inputDescricao)) {
$inputDescricao = $membro->descricao;
}
if (isset($inputImagem)) {
Storage::delete($membro->imagem);
$inputImagem = $req->file('input-imagem')->store('storage/equipa');
} else {
$inputImagem = $membro->imagem;
}
}
$timestamp = date('Y-m-d H:i:s');
DB::table('equipa')
->where('id', $id)
->update([
'nome' => $inputNome,
'email' => $inputEmail,
'facebook' => $inputFacebook,
'instagram' => $inputInstagram,
'profissao' => $inputProfissao,
'descricao' => $inputDescricao,
'imagem' => $inputImagem,
'updated_at' => $timestamp
]);
return redirect('/editar/equipa/')->with('status', 'Membro da equipa atualizado com sucesso');
}
you must use below code after define $validator
$validator = Validator::make($req->all(), [
'input-email' => 'email:rfc,dns|required'
], $erros);
if ($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}
I would like to display the field form.childNumber and form.childFoyerFiscal according to the answer of form.child
If the person chosen TRUE :
-- Display"enfantNombre" and "enfantFoyerFiscal"
If the person chosen is FALSE:
- Do not display anything
All this must change without refreshing the page (with AJAX for example)
Something like that :
class SimulationType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
/* Partie 1 - Situation */
->add('situationFamilliale', ChoiceType::class,$this->getConfigurationChoice("Votre situation familliale ?", "input"))
->add('anneeDeNaissance', IntegerType::class,$this->getConfigurationInteger("Quelle est votre année de naissance ?", "input"))
->add('enfant', ChoiceType::class,$this->getConfigurationBoolean("Avez vous des enfants ?", "radioButton"))
->add('enfantNombre', IntegerType::class,$this->getConfigurationInteger("Combien avez-vous d'enfants ?", "input"))
->add('enfantFoyerFiscal', IntegerType::class,$this->getConfigurationInteger("Combien sont encore dans votre foyer fiscal ?", "input"))
->add('pension', ChoiceType::class, $this->getConfigurationBoolean("Payez vous une pension ?", "radioButton"))
->add('pensionPrix', IntegerType::class, $this->getConfigurationInteger("Combien vous coûte cette pension mensuellement?", "input"))
/* Partie 2 - Patrimoine */
->add('residencePrincipale', ChoiceType::class, $this->getConfigurationResidence("Concernant votre résidence principale vous êtes :", "radioButton", "Proprietaire", "Locataire", "Heberge gratuitement"))
// Propriétaire
->add('creditResidencePrincipale', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous un crédit sur la résidence principale ?", "radioButton"))
// Propriétaire -> Oui
->add('proprietaireCreditPrix', IntegerType::class, $this->getConfigurationInteger("Combien vous coûte ce crédit par mois ?", "input"))
->add('proprietaireCreditTemps', IntegerType::class, $this->getConfigurationInteger("Quelle est la durée restante (en année) ?", "input"))
//Locataire
->add('locataireCreditLoyer', IntegerType::class, $this->getConfigurationInteger("Quel est la montant de votre loyer /mois ?", "input"))
//Investissement Locatif
->add('investissement_bis', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous déjà un investissement locatif en cours ?", "radioButton"))
//Investissement Locatif -> Oui
->add('investissement', CollectionType::class, ['entry_type' => InvestissementType::class, 'allow_add' => true]) // Créer les différents investissements
// Credit (Autres qu'immobilier)
->add('credit', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous des crédits? (Autres qu'immobilier)", "radioButton"))
//Credit (Autres qu'immobilier) --> Oui
->add('creditAdd', CollectionType::class, ['entry_type' => CreditType::class, 'allow_add' => true])
->add('revenuMensuel', IntegerType::class, $this->getConfigurationInteger("Quel est le revenu net MENSUEL de votre foyer ?", "input"))
/* Partie 3 - Epargne */
->add('epargne', ChoiceType::class, $this->getConfigurationEpargne("A combien estimez-vous votre épargne?", "radioButton", "Moins de 10.000€", "Entre 10.000€ et 20.000€", "Entre 20.000€ et 50.000€", "Entre 50.000€ et 100.000€", "Plus de 100.000€"))
->add('apportInvestissement', ChoiceType::class, $this->getConfigurationBoolean("Envisagez vous de mettre un apport dans votre investissement?", "radioButton"))
// qpportInvestissement -> Oui
->add('apportPrix', IntegerType::class, $this->getConfigurationInteger("Combien apporteriez-vous ?", "input"))
->add('reductionImpot', ChoiceType::class, $this->getConfigurationBoolean("Avez-vous déjà des réductions d'impôts ?", "radioButton"))
// reductionImpot -> Oui
->add('reductionImpotPrix', IntegerType::class, $this->getConfigurationInteger("De combien réduisez vous votre impôt par an ?", "input"))
/* Partie 4 - Objectifs */
->add('objectifsPrincipaux', ChoiceType::class, $this->getConfigurationObjectifsPrincipaux("Choisissez vos 3 objectifs principaux", "radioButton", "input", "input1", "input2", "input3", "input4", "input5", "input6"))
->getForm();
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Client::class,
]);
}
/**
* Permet d'avoir la configuration de base d'un IntegerType
*
* #param string $label
* #param string $class
* #return array
*/
private function getConfigurationInteger($label, $class){
return [
'label' => $label,
'attr' =>[
'class' => $class
],
'required' => true
];
}
/**
* Permet d'avoir la configuration de base d'un button de type RADIO
*
* #param string $label
* #param string $class
* #return array
*/
private function getConfigurationBoolean($label, $class): array
{
return [
'label' => $label,
'attr' =>[
'class' => $class
],
'choices' => [
'Oui' => true,
'Non' => false,
],
'expanded' => false,
'multiple' => false,
];
}
/*
* Permet d'avoir le choix en plusieurs proprositions (Max 5)
* L'utilisation de cette function peut servir quand il y a plusieurs choix à faire.
*
*/
public function getConfigurationObjectifsPrincipaux($label, $class, $choix1, $choix2, $choix3, $choix4, $choix5, $choix6, $choix7): array
{
return [
'label' => $label,
'attr' =>[
'class' => $class
],
'choices' => [
$choix1 => "patrimoineImmobilier",
$choix2 => "antipationRetraite",
$choix3 => "reductionFiscalite",
$choix4 => "augmentationRendementEpargne",
$choix5 => "constitutionCapital",
$choix6 => "transmissionEnfant",
$choix7 => "revenuComplementaire",
],
'expanded' => true,
'multiple' => true,
];
}
/*
* Configuration de base d'un ChoiceType
* Permet d'avoir le choix en plusieurs proprositions (Max 5)
* L'utilisation de cette function peut servir quand il y a plusieurs choix à faire.
*
*/
public function getConfigurationResidence($label, $class, $choix1, $choix2, $choix3): array
{
return [
'label' => $label,
'attr' =>[
'class' => $class
],
'choices' => [
$choix1 => strtolower(str_replace(' ','',$choix1)),
$choix2 => strtolower(str_replace(' ','',$choix2)),
$choix3 => strtolower(str_replace(' ','',$choix3)),
],
'expanded' => false,
'multiple' => false,
];
}
/*
* Configuration de base d'un ChoiceType
* Permet d'avoir le choix en plusieurs proprositions (Max 5)
* L'utilisation de cette function sert quand il y a plusieurs choix à faire.
*
*/
public function getConfigurationEpargne($label, $class, $choix1, $choix2, $choix3, $choix4, $choix5): array
{
return [
'label' => $label,
'attr' =>[
'class' => $class
],
'choices' => [
$choix1 => "10k",
$choix2 => "20k",
$choix3 => "50k",
$choix4 => "100k",
$choix5 => "1000k",
],
'expanded' => false,
'multiple' => false,
];
}
/**
* L'utilisation de cette fonction est unique (Partie 1)
*
* #param $label
* #param $class
* #return array
*/
private function getConfigurationChoice($label, $class): array
{
return
[
'label' => $label,
'attr' =>[
'class' => $class
],
'choices' => [
'Célibataire' => 'celibataire',
'Marié(e)' => 'marie',
'Pacsé(e)' => 'pacse',
'En concubinage' => 'concubinage',
'Divorcé(e)' => 'divorce',
'Veuf/Veuve' => 'veuf'
]
];
}
SimulationController
class SimulationController extends AbstractController
/**
* #Route("/simulation", name="simulation")
* #param Request $request
* #param ObjectManager $manager
* #return Response
*/
public function formulaire(Request $request, ObjectManager $manager)
{
$Client = new Client();
$form = $this->createForm(SimulationType::class, $Client); //SimulationType = Formulaire avec les champs
/**
* Permet d'agir en fonction des résultats des formulaires
*/
$form->handleRequest($request);
dump($Client);
/* Est ce que le formulaire est bien valide ? */
if ($form->isSubmitted() && $form->isValid()) {
// Si la formulaire est correct --> Direction la page Patrimoine
return $this->render('content/verification.html.twig', [
'form' => $form->createView()]);
} elseif ($form->isSubmitted() && $form->isValid() == false) {
// Si la page n'est pas correct, il affiche la page de vérification
return $this->render(
'/content/verification.html.twig', [
'form' => $form->createView()]);
} else {
return $this->render(
'/content/simulation.html.twig', [
'form' => $form->createView()]);
}
}
You've to use Form Events to make your form element update if another form element is updated. That is quite complicated. On the symfony doc you can find an example.
I'm using Respect to validate some forms in a project but this project is in Spanish and I don't understand how messages work after spending a long time reading the documentation and even its code.
I'm using Slim and I'm using a NestedValidationException following an example I read on a tutorial on Youtube.
This is the validate method:
public function validate($request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
//In English it's enough with
//$this->errors[$field] = $e->getMessages();
$this->$errors[$field] = $e->getMainMessage();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
I've seen some responses before but some are very hard to grasp for me as I don't intend on doing a whole translation of the library. I'm just attempting to write 5 or 6 custom messages.
EDIT: A method using the messages:
$validation = $this->c->validator->validate($request, [
'username' => v::noWhitespace()->notEmpty()->usernameAvailable(),
'email' => v::noWhitespace()->notEmpty()->email()->emailAvailable(),
'password1' => v::noWhitespace()->notEmpty(),
'password2' => v::noWhitespace()->notEmpty()->identical($inputPassword),
]);
Using findMessages with the parameter you're translating the messages. You just have to replace the content in the catch block:
catch (NestedValidationException $e) {
$errors = $e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
$filteredErrors = array_filter($errors); // Ensure the array is not containing empty values
$this->$errors[$field] = $filteredErrors;
}
This is my first time with prestashop and following the docs I was able to create a simple module that store some text.
I want to modify it and add the possibility to upload an image...on this scenario the docs is very poor so I tried myself and I was ablo to upload it but if I try to pass the image to the fronend all I get is NULL.
This is my configuration file:
<?php if ( ! defined('_PS_VERSION_') ) exit;
class Stilogopopup extends Module
{
public function __construct()
{
$this->name = 'stilogopopup';
$this->tab = 'front_office_features'; //Indica dove posizionare il modulo (http://doc.prestashop.com/display/PS15/Creating+a+PrestaShop+module)
$this->version = '1.0.0';
$this->author = 'Christian Giupponi STILOGO';
$this->need_instance = 0; //Indica se il modulo deve essere caricato quando si entra nel backoffice 0=no 1=si
$this->ps_versions_compliancy = array('min' => '1.5');
parent::__construct();
$this->displayName = $this->l('STILOGO PopUp');
$this->description = $this->l('Permette di mostrare un PopUp contenente un testo o una immagine');
$this->confirmUninstall = $this->l('Sicuro di voler disinstallare questo modulo?');
if( ! Configuration::get('STILOGOPOPUP_NAME') )
{
$this->warning = $this->l('Non è stato fornito nessun nome');
}
}
/*
* Installazione
* In questa funzione definisco anche gli hook per il frontend.
* Un elenco degli hook disponibili:
* http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5
*/
public function install()
{
if( parent::install() == false )
{
return false;
}
//Registro un hook per la homepage
if( ! $this->registerHook('displayHome') )
return false;
//Registro un hook per aggiungere dati all'header
if( ! $this->registerHook('displayHeader') )
return false;
Configuration::updateValue('STILOGOPOPUP_NAME', 'popup');
//Fatto
return true;
}
public function uninstall()
{
if( ! parent::uninstall() )
{
return false;
}
if( ! Configuration::deleteByName('STILOGOPOPUP_NAME') )
{
return false;
}
return true;
}
/*
* Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
* displayHome
* In questo modo posso inviare al frontend delle variabili per essere utilizzate
* dal template engine smarty.
* E' un semplice array che assegna alle variabili il valore delle configurazioni
* e recupera il file template che contiene il codice da mostrare in home
*/
public function hookDisplayHome( $params )
{
$this->context->smarty->assign(
array(
'stilogopopup_testo' => Configuration::get('STILOGOPOPUP_TEXT'),
'stilogopopup_titolo' => Configuration::get('STILOGOPOPUP_TITLE'),
'stilogopopup_image' => Configuration::get('STILOGOPOPUP_IMAGE'),
'stilogopopup_link' => $this->context->link->getModuleLink('stilogopopup', 'display')
)
);
return $this->display(__FILE__ , 'stilogopopup.tpl');
}
/*
* Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
* displayHeader
* e permette di inserire all'interno dei tag <head> del codice aggiuntivo,
* Utile quando si ha la necessità di inserire file css o js
*/
public function HookDisplayHeader()
{
$this->context->controller->addCSS($this->_path.'css/stilogopopup.css', 'all');
$this->context->controller->addJS($this->_path.'js/stilogopopup.js', 'all');
}
/*
* Questa funzione è utilizzata nel backend di prestashop per mostrare il form di configurazione
* del modulo.
* Gestisce sia il salvataggio dei parametri di configurazione che la stampa del form (tramite funzione esterna)
*/
public function getContent()
{
$output = null;
//Controllo se devo salvare dei dati
if( Tools::isSubmit('submit'.$this->name) )
{
//Recupero i valori degli input
$stilogopopup_text = strval(Tools::getValue('STILOGOPOPUP_TEXT'));
$stilogopopup_title = strval(Tools::getValue('STILOGOPOPUP_TITLE'));
$stilogo_image = $_FILES['STILOGOPOPUP_IMAGE'];
//Controllo se c'è una immagine da salvare
if( $stilogo_image['name'] != "" )
{
//Formati accettati
$allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
//Controllo che l'immagine sia in un formato accettato
if( in_array($stilogo_image['type'], $allowed) )
{
$path = '../upload/';
//Controllo se esiste già un file con questo nome
//Carico il file
if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
{
$output .= $this->displayError( $path.$stilogo_image['name'] );
return $output.$this->displayForm();
}
}
else
{
$output .= $this->displayError( $this->l('Formato immagine non valido.') );
return $output.$this->displayForm();
}
}
//Controllo se i campi obbligatori sono effettivamente stati riempiti
if( ! $stilogopopup_title || empty($stilogopopup_title) || ! Validate::isGenericName($stilogopopup_title) )
{
$output .= $this->displayError( $this->l('Devi inserire un titolo.') );
return $output.$this->displayForm();
}
//Se arrivo qui è perchè tutti i campi obbligatori sono stati riempiti quindi aggiorno i valori
Configuration::updateValue('STILOGOPOPUP_TEXT', $stilogopopup_text);
Configuration::updateValue('STILOGOPOPUP_TITLE', $stilogopopup_title);
Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);
$output .= $this->displayConfirmation( $this->l('Impostazioni salvate') );
}
//Richiamo la funzione di stampa del form e concateno il ritultato (se c'è) del salvataggio
return $output.$this->displayForm();
}
/*
* Questa è la funzione che si occupa di generare il form di configurazione del modulo.
* Viene richiamata dalla funzione getContent e permette di definire dei campi da mostrare all'utente.
* Per generare i campi si utilizza un semplice array.
* Qui un elenco di tutti i tipi supportati:
* http://doc.prestashop.com/display/PS15/HelperForm
*/
public function displayForm()
{
//Recupero la lingua di default
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
//Creo i campi del form
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Impostazioni')
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Titolo del PopUp'),
'name' => 'STILOGOPOPUP_TITLE',
'required' => true
),
array(
'type' => 'textarea',
'label' => $this->l('Testo del PopUp'),
'name' => 'STILOGOPOPUP_TEXT',
'required' => false
),
array(
'type' => 'file',
'label' => $this->l('Inserisci una immagine'),
'name' => 'STILOGOPOPUP_IMAGE',
'display_image' => true,
'required' => false
),
),
'submit' => array(
'title' => $this->l('Salva'),
'class' => 'button'
),
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> rimuove la toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' => array(
'desc' => $this->l('Salva'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Carico i valori correnti
$helper->fields_value['STILOGOPOPUP_TEXT'] = Configuration::get('STILOGOPOPUP_TEXT');
$helper->fields_value['STILOGOPOPUP_TITLE'] = Configuration::get('STILOGOPOPUP_TITLE');
//Genero il form
return $helper->generateForm($fields_form);
}
}
?>
As you can see I have added in the displayForm function this code that should add a file input:
array(
'type' => 'file',
'label' => $this->l('Inserisci una immagine'),
'name' => 'STILOGOPOPUP_IMAGE',
'display_image' => true,
'required' => false
),
and it does...in the getContent, where according to the docs all the save/display should live I get the image with PHP (does prestashop have a better built in solution for this?) in this way:
$stilogo_image = $_FILES['STILOGOPOPUP_IMAGE'];
//Controllo se c'è una immagine da salvare
if( $stilogo_image['name'] != "" )
{
//Formati accettati
$allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
//Controllo che l'immagine sia in un formato accettato
if( in_array($stilogo_image['type'], $allowed) )
{
$path = '../upload/';
//Controllo se esiste già un file con questo nome
//Carico il file
if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
{
$output .= $this->displayError( $path.$stilogo_image['name'] );
return $output.$this->displayForm();
}
}
else
{
$output .= $this->displayError( $this->l('Formato immagine non valido.') );
return $output.$this->displayForm();
}
}
Then I saved just the image name here:
Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);
and I send it to the front end in the hookDisplayHome function in this way:
$this->context->smarty->assign(
array(
'stilogopopup_testo' => Configuration::get('STILOGOPOPUP_TEXT'),
'stilogopopup_titolo' => Configuration::get('STILOGOPOPUP_TITLE'),
'stilogopopup_image' => Configuration::get('STILOGOPOPUP_IMAGE'),
'stilogopopup_link' => $this->context->link->getModuleLink('stilogopopup', 'display')
)
);
return $this->display(__FILE__ , 'stilogopopup.tpl');
The problem is that the smarty variable $stilogopopup_image is NULL and I can see it just if I add in my view the {debug} tag.
What is the problem? The other fields works
in getContent() function you use the "$stilogo_image" variable, but for save to DB (Configuration::updateValue()) you are use another variable the "$stilogopopup_image".
I think this is the main reason of empty value in Configuration::get('STILOGOPOPUP_IMAGE')
Regards