Kohana orm validation - kohana

I have fully working validation script my problem is that i can't get custom error messages
Here is my function for registration: http://pastebin.com/ZF3UVxUr
And here is my message array: http://pastebin.com/d9GUvM3N
my messages script is in: \application\messages\registration.php Any suggestions?
Sorry about long code just skip html and other stuff

If you're catching the validation exception that is thrown by the User model, then likely your messages file location is incorrect. It needs to be: 'registration/user.php'.
// ./application/messages/registration/user.php
return array(
'name' => array(
'not_empty' => 'Please enter your username.',
),
'password' => array(
'matches' => 'Passwords doesn\'t match',
'not_empty' => 'Please enter your password'
),
'email' => array(
'email' => 'Your email isn\'t valid',
'not_empty' => 'Please enter your email'
),
'about-me' => array(
'max_length' => 'You cann\'ot exceed 300 characters limit'
),
'_external' => array(
'username' => 'This username already exist'
)
);
Also, contrary to Michael P's response, you should store all validation logic in the model. Your controller code, to register a new user, should be as simple as:
try
{
$user->register($this->request->post());
Auth::instance()->login($this->request->post('username'), $this->request->post('password'));
}
catch(ORM_Validation_Exception $e)
{
$errors = $e->errors('registration');
}

You should be validating the post data before attempting to hit any models. Your validation rules are not being executed because you haven't performed a validation check().
I would do something like:
// ./application/classes/controller/user
class Controller_User extends Controller
{
public function action_register()
{
if (isset($_POST) AND Valid::not_empty($_POST)) {
$post = Validation::factory($_POST)
->rule('name', 'not_empty');
if ($post->check()) {
try {
echo 'Success';
/**
* Post is successfully validated, do ORM
* stuff here
*/
} catch (ORM_Validation_Exception $e) {
/**
* Do ORM validation exception stuff here
*/
}
} else {
/**
* $post->check() failed, show the errors
*/
$errors = $post->errors('registration');
print '<pre>';
print_r($errors);
print '</pre>';
}
}
}
}
Registration.php stays mostly the same, with the exception of fixing up the 'lenght' spelling mistake you had:
// ./application/messages/registration.php
return array(
'name' => array(
'not_empty' => 'Please enter your username.',
),
'password' => array(
'matches' => 'Passwords doesn\'t match',
'not_empty' => 'Please enter your password'
),
'email' => array(
'email' => 'Your email isn\'t valid',
'not_empty' => 'Please enter your email'
),
'about-me' => array(
'max_length' => 'You cann\'ot exceed 300 characters limit'
),
'_external' => array(
'username' => 'This username already exist'
)
);
Then, sending an empty 'name' field will return:
Array
(
[name] => Please enter your username.
)

Related

Codeigniter 4 registration to multiple table

I have some questions that I do not know how to solve it. Currently I have 2 tables, users and user_profile. I have 2 fields in users_profile, membership and coins which will be added by a default value "yes/no" for membership and "0" for coins.
How do I add "created_by" column from the form username?
How do I add the value in the user_profile table when the user submit the registration form?
This is my code that will store the registration form fields in users table
public function register()
{
$data = [];
helper(['form']);
$validation = \Config\Services::validation();
// To add in is_unique
if($this->request->getMethod() == 'post'){
//validations
$rules = [
'username' => 'required|is_unique[users.username]',
'email' => 'required|valid_email|is_unique[users.email]',
'firstname' => 'required',
'lastname' => 'required',
'dob' => 'required',
'country' => 'required',
'contact' => 'required',
'password' => 'required'
];
$errors = [
'username' => [
'is_unique' => 'Username already exist!'
],
'email' => [
'is_unique' => 'Email already exist!'
]
];
if(!$this->validate($rules, $errors)){
$data['validation'] = $this->validator;
}else{
//store information into database
$model = new AccountModel();
$newData = [
'username' => $this->request->getVar('username'),
'email' => $this->request->getVar('email'),
'firstname' => $this->request->getVar('firstname'),
'lastname' => $this->request->getVar('lastname'),
'dob' => $this->request->getVar('dob'),
'country' => $this->request->getVar('country'),
'contact' => $this->request->getVar('contact'),
'password' => $this->request->getVar('password'),
'created_by' => $this->request->getVar('username')
];
$model->save($newData);
$user_id = $model->insertID();
$newAccount = $model->where('user_id',$user_id)->first();
$userProfileModel = new UserProfileModel();
$newProfile = $userProfileModel->save(['user_id' => $user_id, 'coins' => '0', 'membership' => 'no']);
}
}
echo view('templates/header', $data);
echo view('account/register');
echo view('templates/footer');
}
AccountModel
class AccountModel extends Model{
protected $table = 'users';
protected $allowedFields = [
'username',
'email',
'firstname',
'lastname',
'dob',
'country',
'contact',
'password',
'created_at',
'updated_at',
'created_by'
];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
protected function beforeInsert(array $data) {
$data = $this->passwordHash($data);
return $data;
}
protected function beforeUpdate(array $data) {
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data){
if(isset($data['data']['password']))
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
return $data;
}
}
UserProfileModel
<?php namespace App\Models;
use CodeIgniter\Model;
class UserProfileModel extends Model{
protected $table = 'user_profile';
protected $allowedFields = [
'user_id',
'coins',
'membership'
];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
protected function beforeInsert(array $data) {
}
protected function beforeUpdate(array $data) {
}
}
?>
How do I add "created_by" column from the form username?
use insertID() ci4 models method aftaer save method executed. It will return the lastest primary key which been saved from the table you want. in this case from your account table
$model->save($newData);
$userId= $model->insertID();
How do I add the value in the user_profile table when the user submit the registration form?
you should have a foreign key in user_profile table that refering to users table primary key
++++++++++++ ++++++++++++++++
+ users + + user_profile +
++++++++++++ ++++++++++++++++
+-id[p.k] + +-id[p.k] +
+-username + +-users_id[f.k]+
+-email + +-coins +
+-email + +-membership +
get lastest user data by $userId, i assume your primary key is 'id' and than save to the user_profile
$newAccount = $model->where('id',$user_id')->first();
$userProfileModel = new UserProfileModel();
$newProfile = $userProfileModel->save(['user_id' => $userId])

I can´t concatenate a label with string in symfony3

I can´t concatenate a label with string.
->add('originador', EntityType::class, array(
'label' => "app.label.x_originador".'*',
'class' => 'AppBundle:Usuario',
'em' => $options['entityManager'],
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u');
},
'placeholder' => '',
'required' => false,
))
In the part of 'label' => "app.label.x_originador".'*',
I need that the result be Originador*,because the label is for required value.
The result that I recieve is app.label.x_originador*
Please, help me to get
Originador* as result.
You can pass the translator service to your form type and translate then concatenate like this:
class MyFormType extends AbstractType
{
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('originador', EntityType::class, array(
'label' => $this->translator->trans('app.label.x_originador',[], 'domain').'*',
'class' => 'AppBundle:Usuario',
'em' => $options['entityManager'],
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u');
},
'placeholder' => '',
'required' => false,
));
}
}
juste replace "domain" with your translation domain.
EDIT: but yeah, the best solution is probably #ccKep's one

Custom Taxonomy and tax_query Issue?

I am working on Plugin development and my plugin name is plugindev.I have a custom post type called team.I have a custom taxonomy Team_Category which is being registered by this code
/***************************taxonomy****************************/
add_action( 'init', 'create_team_taxonomies', 0 );
function create_team_taxonomies() {
// Add new taxonomy, make it hierarchical (like categories)
$labels = array(
'name' => _x( 'Team_Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Team_Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Team_Categories' ),
'all_items' => __( 'All Team_Categories' ),
'parent_item' => __( 'Parent Team_Category' ),
'parent_item_colon' => __( 'Parent Team_Category:' ),
'edit_item' => __( 'Edit Team_Category' ),
'update_item' => __( 'Update Team_Category' ),
'add_new_item' => __( 'Add New Team_Category' ),
'new_item_name' => __( 'New Team_Category Name' ),
'menu_name' => __( 'Team_Category' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => false,
'query_var' => true,
'rewrite' => array( 'slug' => 'Team_Category' ),
);
register_taxonomy( 'Team_Category', array( 'team' ), $args );
}
/****************************taxanomy end***********************************/
But when I use a tax_query in my WP_Query, I do not get any posts.
here is my code
<?php
$taxonomy_name = 'Team_Category';
$get_categories = get_terms($taxonomy_name);
$total_categories = count($get_categories);
// Loop through the obituaries:
for ($i = 0; $i < $total_categories; $i++) {
?>
<div class="row">
<div class="col-md-4">
<?php echo $category_name = $get_categories[$i]->name; ?>
</div>
<?php
$args = array(
'post_type' => 'team',
'tax_query' => array(
array(
'taxonomy' => 'Team_Category',
'field' => 'slug', 'terms' => $category_name,)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title();
}
}
wp_reset_query(); ?>
</div>
<?php }
It works perfectly without tax_query.I did lot of google but found no suitable result.Any solution to solve this problem .Any help would be highly appreciated
register_taxonomy()
$taxonomy (string) (required) The name of the taxonomy. Name should
only contain lowercase letters and the underscore character, and not
be more than 32 characters long (database structure restriction).
change your taxonomy name from Team_Category to team_category
you should then be able to use argument like this
$arg = array(
'post_type' => 'team',
'taxonomy' => 'team_category',
'term' => 'term_name',
);
//using tax_query
$mytax = get_terms('your_taxonomy');
$arg = array(
'post_type' => 'team',
'tax_query' => array(
array(
'taxonomy' => 'team_category',
'field' => 'slug',
'terms' => 'term_slug', //you need to use slug not name $mytax[0]->slug;
#or
//'field' => 'name',
//'terms' => 'term_name', //you need to use term name $mytax[0]->name;
#or
//'field' => 'term_id',
//'terms' => 'term_ID', //you need to use term ID $mytax[0]->term_id;
),
),
);
WP_Query($nivelquery) and the loop will now print every post registered using my custom taxonomy in $terms, and order them by the meta_key 'salary'.
$terms = get_terms('Team_Category',
array(
'orderby' => 'slug',
'order' => 'ASC',
'hide_empty' => 1,
'fields' => 'ids',
));
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'vagas_tipo',
'field' => 'id',
'terms' => $terms,
),
),
'orderby' => 'meta_value',
'meta_key' => 'salary',
'order' => 'DESC'
);
$query = new WP_Query($args);

Exclude custom taxonomy

I have a custom post type 'listings' and one of its taxonomies is 'status'. I want to create two widgets:
display all 'listings' WITH 'status' 'sold'.
display all 'listings' WITHOUT 'status' 'sold'.
I've achieved the first widget using
query_posts( array(
'status' => 'sold' )
);
I can't create the second widget. It should be like "status => !sold", or exclude sold. Any ideas?
Try below code when you need status = sold
$args = array(
'post_type' => 'listing',
'meta_query' => array(
array(
'key' => 'status',
'value' => 'sold',
'compare' => 'LIKE'
)
)
);
$myQuery = new WP_Query($args);
And below code when you want status != sold
$args1 = array(
'post_type' => 'listing',
'meta_query' => array(
array(
'key' => 'status',
'value' => 'sold',
'compare' => 'NOT LIKE'
)
)
);
$myQuery1 = new WP_Query($args1);
This works perfectly...
query_posts( array(
'post_type' => 'listings',
'tax_query' => array(
array(
'taxonomy' => 'status',
'field' => 'slug',
'terms' => 'sold',
'operator' => 'NOT IN'
),
)
)
);
This code excludes status => sold from post_type => listings

CakePHP Search plugin search in many fields

I'm using CakePHP search plugin http://cakedc.com/downloads/view/cakephp_search_plugin and want to make an arg to search multiple fields I have the array filterArgs as follows
var $filterArgs = array(
array('name' => 'search', 'type' => 'like', 'field' => 'Interview.title_en'),
);
I want the search arg to search not only the field Interview.title_en but to search also another field I tried something like
var $filterArgs = array(
array('name' => 'search', 'type' => 'like', 'field' => array('Interview.title_en', 'Interview.Desc'));
but It doesn't work!!
Any suggestions?
In order to achieve this, you have to create a simple method in your model which builds the 'OR' conditions for searching the fields.
public $filterArgs = array(
array('name' => 'q', 'type' => 'query', 'method' => 'filterQuery'),
);
public function filterQuery($data = array()) {
if(empty($data['q'])) { // q is the name of my search field
return array();
}
$query = '%'.$data['q'].'%';
return array(
'OR' => array(
'Model.title LIKE' => $query,
'Model.description LIKE' => $query,
'Model.resources LIKE' => $query,
)
);
}

Resources