How to add regex to attribute name in custom validations in Laravel? - regex

In custom validation as shown below:
'custom' => array(
'attribute-name' => array(
'rule-name' => 'custom-message',
),
),
How is it possible to define regex along with the attribute-name-{regex} as well?!
Example:
'custom' => array(
'institute_regex:{/d{1}}' => array(
'required' => 'the field is required',
),
),

I think that might be what you were looking for ages ago, but anyway, here is what I did.
Had to find a way to define custom validation messages (in another language) for inputs dynamically generated in the frontend. The result is that I would get the following type of classes:
project_name-1, -2, -3 etc to keep it simple.
So what I did, and it worked just fine for me was adding the following lines to my validation.php file (whatever the language is):
'project_name-*' => [
'required' => 'Please name your project.',
],
And voilĂ , I hope it will help someone!

Related

CakePHP - Router::url doesn't build pretty URLs when there's a regex match in the Router::connect

In my CakePHP, my routes.php file looks like this:
Router::connect('/premios/:category',
array('controller' => 'prizes', 'action' => 'category'),
array(
'category' => '\bmarcas|restaurantes|combustibles|peluqueria\b',
));
This way whenever a user enters the /premios url, the next parameter is matched with the "category" regex. This works perfect.
The problem is that when I want to generate a pretty url for the category, let's say, "peluqueria", using this line of code generates a "non-pretty" url:
Router::url(array('controller' => 'prizes', 'action' => 'category', 'peluqueria')); ?>
Instead of generating a pretty URL (/premios/peluqueria) it generates a non pretty url (/prizes/category/peluqueria).
What am I doing wrong? Or is this a limitation of the Router::url function?
A workaround would be to define every connect, avoiding the regex, but it isn't a pretty as the current solution plus it would get annoying when the categories count start to grow.
Any ideas?
You have to actually name the category parameter in Router::url, like this
Router::url(array('controller' => 'prizes',
'action' => 'category',
'category' => 'peluqueria'));
And you'd probably want to pass that "category" parameter to the category action in Prizes, so you're missing something
Router::connect(
'/premios/:category',
array('controller' => 'prizes', 'action' => 'category'),
array(
'pass' => array('category'),
'category' => '\bmarcas|restaurantes|combustibles|peluqueria\b'
)
);
Look this part of the docs with more detention :)

How to set the default selected value for a Doctrine ObjectRadio element

I've got a simple user registration form where a user can choose their own user type. The user type maps to a role. This is part of a zf2 application using the doctrine2 module.
The relevant part of the init() method of my user fieldset looks like this:
public function init()
{
// ... other field definitions ...
$roleRadio = new ObjectRadio('role');
$roleRadio->setLabel('What type of user are you?')
->setOptions(
array(
'object_manager' => $this->objectManager,
'target_class' => 'MyUser\Entity\Role',
'property' => 'roleId',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('userselectable' => true),
'orderBy' => array('displayorder' => 'ASC'),
),
),
)
);
$this->add($roleRadio);
// ... more stuff ...
}
I'm using Doctrine's ObjectRadio class for this element to automatically populate the value options. Is there any way to set the default selected value?
I know I can just do something like this:
$form->get('user')->get('role')->setValue(3);
But I don't want to hard code this and I also don't want to put that kind of logic in my controller.
Any suggestions?
I don't know what do you mean by "I don't want to hard code this", but you can do it as you said in your controller, or you can do it in the form definition by setting attributes as the following:
$roleRadio->setAttributes(array('value' => 3));

How to use DoctineModule ObjectSelect based on custom repository method?

I have a table with a list of person that belong to different categories A and B for example. My problem is that i have a form with DoctrineModule ObjectSelect and i want to show in the ObjectSelect only the name of persons of Category A.
I find this https://github.com/doctrine/DoctrineModule/blob/master/docs/form-element.md#example-3--extended-version but the example is not clear for me and i don't know how to adapt it to my case.
Thank you.
excuse me for my english.
It's actually quite similar to the example you were looking at (I guess that's why there is no example for it), the only difference is that instead of using find/findBy/... you pass your custom repository name as name key, with code similar to this:
$this->add(array(
'name' => 'my-select-object',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'attributes' => array(
),
'options' => array(
'label' => 'My Label',
'object_manager' => $entityManager,
'target_class' => 'Application\Entity\MyEntity',
'property' => 'name',
'is_method' => true,
'find_method' => array(
'name' => 'myCustomRepositoryMethod',
'params' => array(
),
),
),
));
Also notice that your entity needs to know about repository existence, so make sure it uses this line:
#ORM\Entity(repositoryClass="Application\Entity\Repository\MyCustomRepository")
So when you open the form with this ObjectSelect it will call you repository method instead of loading the dropdown directly. That method should just return an array of entity objects which are then used by ObjectSelect to generate select element's options.

CakePHP 2.0 twitter-like follow button

I can't help myself and it's currently annoying, and yes, I used google a lot.
What I need:
A twitterlike follow button with the action to follow user.
What I already did:
Database
users table: id, username, password, ...
users_users table: id, user_id, follower_id
Code
In model User.php
public $hasAndBelongsToMany = array(
'Follower' => array(
'className' => 'User',
'joinTable' => 'users_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'follower_id',
'unique' => 'keepExisting',
)
);
In UsersController.php
public function follow() {
/*need help here*/
}
In Users\index.ctp
<?php if ($current_user['id'] != $user['User']['id']) echo $this->Html->link('Follow', array('action' => 'follow', $user['User']['id'])); ?>
Personally, I don't find hasAndBelongsToMany to be a good fit for situations like this. It's a good fit for when you want to display a list of checkboxes, or a select list, and allow the user to select/manage all their followings (or whatever the relationships might be) in one form.
It might just be my personal preference, but in situations like yours, where you're adding/deleting single links without worrying about any of the other links related to that user, I prefer to just create a separate 'Relationships' (or similarly named) Model / Controller, and consider the records as things in their own right, as opposed to just hasAndBelongsToMany links that are all sort of 'automagically' managed.
Here's how I'd do it:
Name your users_users table 'relationships'. And name the columns 'followed_by_id' and 'following_id' (or similar) to avoid any ambiguity as to which user is the follower / followee (if that was a word!).
In your users Model, you'd have these relationships:
var $hasMany = array(
'Followers' => array(
'className' => 'Relationship',
'foreignKey' => 'following_id',
'dependent'=> true
),
'FollowingUsers' => array(
'className' => 'Relationship',
'foreignKey' => 'followed_by_id',
'dependent'=> true
),
);
Then you'd have a Relationships model that looks something like this (the $belongsTo relationships are the important part):
<?php
class Relationship extends AppModel {
var $name = 'Relationship';
var $validate = array(
'followed_by_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'following_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
var $belongsTo = array(
'FollowedBy' => array(
'className' => 'User',
'foreignKey' => 'followed_by_id'
),
'Following' => array(
'className' => 'User',
'foreignKey' => 'following_id'
)
);
}
?>
And then in your Relationships controller, you'd have something like this:
function add($following_id = null) {
$this->Relationship->create();
$this->Relationship->set('followed_by_id',$this->Auth->User('id'));
$this->Relationship->set('following_id',$following_id);
if ($this->Relationship->save($this->data)) {
// all good
} else {
// You could throw an error here if you want
$this->Session->setFlash(__('Error. Please, try again.', true));
}
$this->redirect($this->referer());
}
Then to add relationships, you obviously just call the add method of your relationships controller.
NOTE: Ideally, since adding a relationship is changing the database, it ideally shouldn't be done with a GET request accessed by a regular URL. It should be done via submitting a form via POST. I know that seems overkill when it's so easy to just do it via a regular link with GET. I haven't bothered to use forms/POST in this example - but if you want to stick to best practices, that's what you should do. See this for more info: https://softwareengineering.stackexchange.com/questions/188860/why-shouldnt-a-get-request-change-data-on-the-server

ZF routing - url with extension with Nth params

Similar to this question, I have accomplished passing the format with the url extension, but you have have to declare the parameters passed upfront. Example:
new Zend_Controller_Router_Route_Regex(
'([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)(\.(\w+))?',
array(
'module' => 'Default',
'controller' => 'index',
'action' => 'index',
),
array(
1 => 'module',
2 => 'controller',
3 => 'action',
4 => 'extension',
5 => 'format'
)
);
But what if I want /:module/:controller/:action/*.:format???
So that no matter how many parameters I pass through the url, the '.whatever' will be the format parameter? Basically, I'm trying to take the default router and add extension as the 'format param'.
Edit:
The issue isn't grabbing the extension, the issue is adding other params. For example
/blogs/posts/view/post/500/foo/bar/format/html
will translate into:
array('module'=>'blogs','controller'=>'posts', 'action' => 'view', 'post'=>500, 'format' => 'html', 'foo' => 'bar');
But I want to be able to represent the format the same route like so:
/blogs/post/view/post/500/foo/bar.html
No matter how many parameters are declared between the action and the format.
Your whatever you can specify with .* expression.
To match it - simply: (.*)
If you want not to grab for example extension, use ?:
(.*?)(\.(\w+))