ZF2 transalation is not working in form class - validation

I am using zendframework 2 and My translations are not working here in form class where the form is formed and there is validation, elsewhere in whole applications they are working properly.
I have pasted all the code in my file with namespaces.
<?php
namespace Services\Form;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ProfilePicForm extends Form implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $sl)
{
$this->serviceLocator = $sl;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function init()
{
$routeMatch = $this->getServiceLocator()->getServiceLocator()->get('Application')->getMvcEvent()->getRouteMatch();
$translator = $this->getServiceLocator()->getServiceLocator()->get('viewHelperManager')->get('translate')->getTranslator();
$action = $routeMatch->getParam('action');
// Form
parent::__construct('profile_pic_form');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$profile_pic_form_csrf = new Element\Csrf('profile_pic_form_csrf');
$profile_pic_form_csrf->setCsrfValidatorOptions(array('timeout'=>'3600'));
$this->add($profile_pic_form_csrf);
$profile_pic = new Element\File('profile_pic');
$this->add($profile_pic);
// Validation
$inputFilter = new InputFilter();
$profile_pic = new Input('profile_pic');
$profile_pic->getFilterChain()
->attach(new \Lib\MyLib\Filter\RenameUpload(array(
'target' => SERVICE_PROFILE_PIC_UPLOAD_PATH.'/profile-pic.*',
'use_upload_extension' => true,
'randomize' => true
)));
$required = true;
$profile_pic->setRequired($required);
$validator = new \Zend\Validator\File\UploadFile();
$validator->setOptions(array(
'messageTemplates' => array(
\Zend\Validator\File\UploadFile::FILE_NOT_FOUND => 'Please select picture.'
)));
$profile_pic->getValidatorChain()->attach($validator,true);
$validator = new \Zend\Validator\File\Size(array('max' => 250*1024));
$validator->setMessage(**$translator->translate('MyAccountPictureErrorMessage1')**);
$profile_pic->getValidatorChain()->attach($validator,true);
$validator = new \Zend\Validator\File\Extension('png,jpg');
$validator->setMessage(**$translator->translate('MyAccountPictureErrorMessage2')**);
$profile_pic->getValidatorChain()->attach($validator,true);
$inputFilter->add($profile_pic);
$this->setInputFilter($inputFilter);
}
this is my controller function.
public function profileAction() {
$this->layout('ajax-layout');
$var = new \stdClass();
$viewmodel = new ViewModel();
$this->authPlugin()->checkLogin();
$this->servicePlugin()->checkSid();
$this->layout()->setVariable('allowedFeatures', $this->featurePlugin()->getAllowedFeatures());
$this->languagePlugin()->translate();
$var->userInfo = $this->authPlugin()->getUserInfo();
if($this->params()->fromRoute('sid') !== null){
$var->sid = $this->params()->fromRoute('sid');
}
elseif ($this->params()->fromRoute('id') !== null) {
$var->sid = $this->params()->fromRoute('id');
}
// ----------------------- i m here --------------------------
// $var->sid = $this->params()->fromRoute('sid');
$var->profilePicForm = $this->getServiceLocator()->get('FormElementManager')->get('\Services\Form\ProfilePicForm');
$var->serviceNameForm = $this->getServiceLocator()->get('FormElementManager')->get('\Services\Form\ServiceNameForm');
$var->service = $this->getServices()->fetchServiceById($var->sid);
// Fetch payment history
$var->paymentHistory = $this->getServiceLocator()->get('Services\Model\PaymentTransactionService')->fetchPaymentTransactionsByServiceId($var->sid);
$var->timezones = $this->getTimeZoneTable()->listAll();
$viewmodel->setVariables(array('var' => $var));
return $viewmodel;
}

This is happening because of your validator.
I already talked about this problem, when you call new validators without the service locator :
https://stackoverflow.com/a/36500438/3333246
To fix that you need to set the translator in your options because:
class Size extends AbstractValidator
abstract class AbstractValidator implements
Translator\TranslatorAwareInterface,
ValidatorInterface
And TranslatorAwareInterface is not initialized if you instanciate a new Validator without ServiceLocator.
So your validators need options declared like this in your code:
$validator = new \Zend\Validator\File\Size(array('translator' => $translator, 'max' => 250*1024));
$validator->setMessage('MyAccountPictureErrorMessage1');
No need to translate the message now, the validator will translate it for you.
For my comment, about your code, nevermind it's not related to your problem. It's just personal in fact.
EDIT:
You don't need this translator :
$translator = $this->getServiceLocator()->getServiceLocator()->get('viewHelperManager')->get('translate')->getTranslator();
But this one
$translator = $this->getServiceLocator()->get('translator');

I have found another way to do this job, i have made an ajax call and on its response i show the divs having the translations.

Related

Yii2 - dynamically switch rules set in model

I want to dynamically substitute rules in model according to switch value on form.
In view:
<?php
$form = ActiveForm::begin([
'enableAjaxValidation' => true,
'validationUrl' => Url::toRoute('anounce/validation')
]);
?>
In controller:
public function actionValidation()
{
$model = new Anounce();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->
request->post())) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
Excerpts from model:
class Anounce extends \yii\db\ActiveRecord
{
private $currentRuleSet; // Current validation set
// Here are arrays of rules with assignment
private $fullRuleSet; // = [...];
private $shortRuleSet; // = [...];
private $minRuleSet; // = [...];
public function init()
{
parent::init();
$this->currentRuleSet = $this->fullRuleSet;
}
public function rules()
{
return $this->currentRuleSet;
}
public function beforeValidate()
{
if ($this->idanounce_type === self::FULL) {
$this->currentRuleSet = $this->fullRuleSet;
} else if ($this->idanounce_type === self::SHORTER) {
$this->currentRuleSet = $this->shortRuleSet;
} else if ($this->idanounce_type === self::MINIMAL) {
$this->currentRuleSet = $this->minRuleSet;
}
return parent::beforeValidate();
}
}
Variable idanounce_type is a switch between rules.
Unfortunately, validation made according to full rules set (or rules set used in init), despite on which *RuleSet value assigned to currentRuleSet.
How to write dynamic switching of rules?
What you want here is to change validation according to the user's input. You can do this by defining scenarios in your model.
So firstly set scenarios where you put in it the fields that are to be validated. Example if you have username, password, and email fields, and you defined two scenarios, in SCENARIO_FIRST only username and password will get validated.
public function scenarios()
{
return [
self::SCENARIO_FIRST => ['username', 'password'],
self::SCENARIO_SECOND => ['username', 'email', 'password'],
];
}
Then in your controller, set the scenario according to the input:
public function actionValidation()
{
$model = new Anounce();
//example
if($condition == true)
{
$model->scenario = Anounce::SCENARIO_FIRST;
}
if (Yii::$app->request->isAjax && $model->load(Yii::$app->
request->post())) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
Read more about scenarios here and how to use them with validation here:
http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios

Saving Model data to database

I have a Report Model which is like the following.
class Report extends Model
{
protected $table = 'reports';
protected $guarded = [];
public function leadsCollection()
{
return $this->hasMany('App\ReportModels\LeadsCollection');
}
}
A Report can have many LeadsCollection, its Model is the following.
class LeadsCollection extends Model
{
protected $table = 'leadsCollection';
protected $guarded = [];
private $xmlElement;
public function __construct($xmlElement = null, $attributes = array()) {
parent::__construct($attributes);
$this->xmlElement = $xmlElement;
}
public function report()
{
return $this->belongsTo('App\ReportModels\Report');
}
function asArray(){
$reportItem = array();
foreach($this->xmlElement->Leads->Lead as $lead) {
$dateIdentified = date("d/m/Y", strtotime($lead->Date));
$reportItem[] = array(
'LeadID' => (string)$lead->ID,
'Client' => (string)$lead->Client->Name,
'Category' => (string)$lead->Category,
'DateIdentified' => $dateIdentified,
'LeadName' => (string)$lead->Name,
'Owner' => (string)$lead->Owner->Name
);
}
return $reportItem;
}
}
Now I am trying to save some data to a database. So I get a list of all Leads by calling my LeadsCollection and passing it an XML list of Leads.
I then loop these Leads and add it to an array. At the same time however I need to save it to the database. This is what I have so far.
public function getForecastReportForLeads() {
$leads = new LeadsCollection(new \SimpleXMLElement(Helper::getCurrentLeads()));
$reportArray = array();
foreach ($leads->asArray() as $lead) {
$report = new Report();
$report->reportName = 'Lead Forecast';
if($report->save()) {
$leads->leadId = $lead['LeadID'];
$leads->leadCategory = $lead['Category'];
$leads->dateIdentified = $lead['DateIdentified'];
$leads->leadName = $lead['LeadName'];
$leads->owner = $lead['Owner'];
$leads->client = $lead['Client'];
$leads->report_id = $report->id;
$leads->save();
$reportItem = array(
'leadData' => $lead
);
$reportArray[] = $reportItem;
}
}
return $reportArray;
}
So I create the Report item, and within the database if I have 7 Leads I end up with 7 Report rows within my reports table, as it should be. However, when I save the Leads, I only end up with 1 row in my leadsCollection table, every other entry seems to be overridden. I think this is because I am not creating the Lead Object within the loop. However, I cant really create it within the loop because I need to loop whats returned when I first create it.
Not sure how clear I am but is there anything I can add to my Model so I can stop any overriding? Or do I need to do this another way?
Thanks
Either you get the variable inside the save method or initialize the new
$report = new Report($reportItem);
$report->save($report)
I'm having a similar Issue right, let me show my code. It would work for your case. My bug is that I'm updating and the plan_detail.id gets moved instead of creating a new one. But if you create would be fine:
public function store(Request $request)
{
$this->validate($request, [ 'title' => 'required',
'description' => 'required']);
$input = $request->all();
$plan_details = Plan_Detail::ofUser()->get();
$plan = new Plan($request->all());
DB::beginTransaction();
Auth::user()->plans()->save($plan);
try {
foreach ($plan_details as $k => $plan_detail)
Plan::find($plan['id'])->details()->save($plan_detail);
DB::commit();
} catch (Exception $e) {
Log::error("PGSQL plan detail " . $e->message());
DB::rollback();
session()->flash('message', 'Error al guardar el plan de entreno');
}
return redirect('plans');
}

Laravel get relationship model within object after save()

I am using laravel 4.2.
I have two models as below :
class User extends Eloquent{
protected $table = 'users';
public function user_card_details(){
return $this->hasMany('User_card_details');
}
}
And
class User_card_details extends Eloquent {
protected $table = 'user_card_details';
public $timestamps = true;
public $softdeletes = true;
public function user(){
return $this->belongsTo('User')->first();
}
}
And I can save the relationship record using :
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user->user_card_details()->save($user_card_details);
Up to this it works fine for me.
After save() , I want the user object should be populated with user_details.
So if I want to use the properties, I can use it like :
echo $user->user_card_details->card_number;
But it is not working now.
Any suggestions?
Thanks
You have to remove the () to get the actual model or collection:
echo $user->user_card_details->card_number;
When you're calling the actual function, you'll receive an instance of the Query builder.
Also, it seems that you're not persisting your $user_card_details-object before you try to bind it to your user:
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user_card_details->save(); //Added this line.
$user->user_card_details()->save($user_card_details);
The more correct way would be:
$user_card_details = [
'card_number' => Input::get( 'card_number' ),
'card_exp_month' => Input::get( 'card_expires_m' ),
'card_exp_year' => Input::get( 'card_expires_y' ),
'card_cvv' => Input::get( 'card_cvv' ),
];
$userCardDetailObj = $user->user_card_details()->create( $user_card_details );
Now, your User_card_detail-instance will be available as the returned object.

Phalcon validation scenario

I used to use Yii framework. I would like to make project using Phalcon. I could not find validation scenario on Phalcon. What is the best way to correctly implement it on Phalcon?
Thanks in advance.
Any data validation:
<?php
use Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\Email;
$validation = new Phalcon\Validation();
$validation->add('name', new PresenceOf(array(
'message' => 'The name is required'
)));
$validation->add('email', new PresenceOf(array(
'message' => 'The e-mail is required'
)));
$validation->add('email', new Email(array(
'message' => 'The e-mail is not valid'
)));
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}
http://docs.phalconphp.com/en/1.2.6/reference/validation.html
If you are working with models:
<?php
use Phalcon\Mvc\Model\Validator\InclusionIn,
Phalcon\Mvc\Model\Validator\Uniqueness;
class Robots extends \Phalcon\Mvc\Model
{
public function validation()
{
$this->validate(new InclusionIn(
array(
"field" => "type",
"domain" => array("Mechanical", "Virtual")
)
));
$this->validate(new Uniqueness(
array(
"field" => "name",
"message" => "The robot name must be unique"
)
));
return $this->validationHasFailed() != true;
}
}
http://docs.phalconphp.com/en/1.2.6/reference/models.html#validating-data-integrity
models also have events, so you can add any logic you need in these functions:
http://docs.phalconphp.com/en/1.2.6/reference/models.html#events-and-events-manager
I would like to use forms for CRUD as they are very dynamic and reusable.
You can achieve that in forms using options.
You can pass additional options to form and act like a scenario.
You can check Form constructor here
https://docs.phalconphp.com/en/latest/api/Phalcon_Forms_Form.html
In your controller you can pass $options
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function insertAction()
{
$options = array();
$options['scenario'] = 'insert';
$myForm = new MyForm(null, $options);
if($this->request->hasPost('insert')) {
// this will be our model
$profile = new Profile();
// we will bind model to form to copy all valid data and check validations of forms
if($myForm->isValid($_POST, $profile)) {
$profile->save();
}
else {
echo "<pre/>";print_r($myForm->getMessages());exit();
}
}
}
public function updateAction()
{
$options = array();
$options['scenario'] = 'update';
$myForm = new MyForm(null, $options);
}
}
And your form should look like something this
<?php
// elements
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
// validators
use Phalcon\Validation\Validator\PresenceOf;
class MyForm extends Form {
public function initialize($entity = null, $options = null) {
$name = new Text('first_name');
$this->add($name);
if($options['scenario'] == 'insert') {
// at the insertion time name is required
$name->addValidator(new PresenceOf(array('message' => 'Name is required.')));
}
else {
// at the update time name is not required
// as well you can add more additional validations
}
}
}
now you can add multiple scenarios and act based on scenarios.

cakephp validation response returning data to controller

Hi i have made a custom validation in the model. How can i access the result($visitor) from this in the controller?
model:
<?php
class Visitors extends AppModel
{
var $name = 'Visitors';
var $validate = array(
'xxx' => array(
'rule' => array('checkxxx'),
'message' => 'yyy.'
)
);
function checkIxxx($check){
$visitor = $this->find('first', array('conditions' => $check));
return $visitor;
}
}
?>
in my controller i want this:
function start() {
$this->Visitors->set($this->data);
if($this->Visitors->validates())
{
if($this->Visitors->xxx->type == 'value') //this is a value from the $visitor array in the model**
{
//do something
}
}
is this possible?
Updated to be a relevant answer, apologies.
//Model
var myField = 'invalid';
function myValidation($var){
if($var === true){
// Passed your validation test
$this->myField = 'valid';
}else{
$this->myField = 'invalid';
}
}
// Controller
$this->Model->set($this->data);
$this->Model->validates($this->data);
if($this->Model->myfield == 'valid'){
// Field has passed validation
}
You will want to use
$this->Model->invalidFields()
PS: You dont follow cake conventions
the model should be "Visitor" (singular)

Resources