Was checking out this tutorial "http://book.cakephp.org/2.0/en/models/data-validation.html" only seem to explain validating on form fields.
So what If I want to validate params or input data.
If I have this controller, where I want to validate a this "campaignId"?:
public function agency($campaignId = null){
if ($this->request->is('get')){
$campaignId;
...
}
CakePHP Model Data Validation is validation of the data, regardless of where it comes from.
If you create an array of data, eg:
$article = array(
'title' => 'Pizza is the Best Food on Earth',
'byline' => 'Dave from StackOverflow',
'content' => 'Pizza is awesome. I love it.'
);
Then try to save it:
$this->Article->save($article);
The Model's validation will kick in and validate (or invalidate) the data.
The most common way data is entered is via a form, but - beyond that, validation is not directly tied to using a form(s).
Related
im learning about angularjs and laravel. Basically i use angular to fetch my data in the forms and than send it to laravel to grab my variables and than create the record, the problem is with one input field (mobile), if i fill the mobile input it doesnt give me any problems, but if i leave it empty (since is not required input) it fails to create the record and give me a undefined index.
How can i make in Laravel to create anyway the record if one variable in my case is empty or not created?
php code:
public function registerUser($inputData)
{
$user = \DB::transaction(function () use ($inputData)
{
$user = User::create([
'email' => $inputData['user']['email'],
'name' => $inputData['user']['name'],
'surname' => $inputData['user']['surname'],
'mobilephone' => $inputData['user']['mobilephone'],
'birth_date' => Carbon::createFromFormat('d-m-Y', $inputData['user']['birth_date']),
]);
$user->save();
//Return the User
return $user;
});
//Return the User instance
return $user;
}
From what you are describing, when you don't fill in the mobile number the front end doesn't send an object which includes "$inputData['user']['mobilephone']". Which would cause an error in the script and prevent it from running. Please post the angular code responsible for transmitting the user information.
If my assumption is correct, you either need to check that these properties all exist in the $inputData before referencing them or have the front end add a dummy value when no value is provided.
OR What ever is holding the record (MySQL or whatever) may not allow this field to be null which would again prevent the insertion. But your description suggests this isn't it.
I have designed page in cakephp contains form which input filed name 'id' and submit button. I want to display the data filtered by the 'id' in view page. Please give me an example with code for this.
So you wanna search into a database for this ID and return back all stored data to the view?
First of all,you have to retrieve your data. See here: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
Secondly, you have to use
$this->set('var_name', $var_name_containing_found_data);
and finally you can handle your data into the view by manipulating as you wish the $var_name variable.
Put this action in your controller:
public function your_action($id = null) {//your action
if ($this->request->is('post')) {
$search = $this->YourModel->find('all', array('conditions' => array('id' => $this->request->data['id'])));//assuming id is submitted like you said $_POST['id']
$this->set('search', $search);
}
}
You can access the search variable in your view (your_view.ctp) like this $this->search
assuming your cakephp version is 2.x
I'm writing an application that uses Zend Framework 2 and Doctrine (both the latest stable version).
There is much documenation (mainly tutorials and blog posts) that deal with saving doctrine entities to the database in combination with Zend Form. Unfortunately they only deal with simple entities that do not have one-to-many or many-to-many relationships.
This is one of those examples that i have adopted into my own code.
http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/
I understand that in the Album Entity of this example, the artist is a string to keep the (already lengthy) tutorial as simple as possible. But in a real world situation this would of course be a one-to-many releationship with an Artist Entity (or even a many-to-many). In the view, a select-box could be displayed where the artist can be selected, listing all the artist-entities that could be found in the database, so the right one can be selected.
Following the example with the album, this is how i've set up an 'edit' Action in my controller:
public function editAction()
{
// determine the id of the album we're editing
$id = $this->params()->fromRoute("id", false);
$request = $this->getRequest();
// load and set up form
$form = new AlbumForm();
$form->prepareElements();
$form->get("submit")->setAttribute("label", "Edit");
// retrieve album from the service layer
$album = $this->getSl()->get("Application\Service\AlbumService")->findOneByAlbumId($id);
$form->setBindOnValidate(false);
$form->bind($album);
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
// bind formvalues to entity and save it
$form->bindValues();
$this->getEm()->flush();
// redirect to album
return $this->redirect()->toRoute("index/album/view", array("id"=>$id));
}
}
$data = array(
"album" => $album,
"form" => $form
);
return new ViewModel($data);
}
How would this example need to be altered if the artist wasn't a string, but an Artist Entity?
And suppose the album also has multiple Track Entities, how would those be processed?
The example would not need to be changed at all, the changes will happen with your entity and your form.
This is a good reference: Doctrine Orm Mapping
So to save yourself a lot of extra work, your OnToMany relationship would use: cascade = persist:
/**
* #ORM\OneToMany(targetEntity="Artist" , mappedBy="album" , cascade={"persist"})
*/
private $artist;
When it comes to persisting the form object, the entity knows it must save the associated entity as well. If you did not include this, then you would have to do it manually using a collection.
To make like easier with your form, you can use Doctrines Object Select like this:
$this->add(
[
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'artist',
'options' => [
'object_manager' => $this->objectManager,
'target_class' => 'Artist\Entity\Artist',
'property' => 'name', //the name field in Artist, can be any field
'label' => 'Artist',
'instructions' => 'Artists connected to this album'
],
'attributes' => [
'class' => '', //Add any classes you want in your form here
'multiple' => true, //You can select more than one artist
'required' => 'required',
]
]
);
So now your form takes care of the collection for you, the controller as per your example does not need to change since the entity will take care of the persisting...
Hope this gets you on track.
I got a problem with my cake validation.
The user enters e.g. "20€" in a form field and I only want to get the number "20" with stripped out Euro-sign. But the validation methods only allow checking if something is what it´s supposed to be.
I´m about to create a function in my rule-set but I´m struggling going further because what the function returns in cake context is either true or false, not a modified variable like I need ...
'rule-3' => array(
'rule' => 'checkEuro',
'message' => 'don´t need one because it should be a conversion only :-('
)
public function checkEuro($data) {
$data = str_replace('€','',$data);
return preg_replace('/[^0-9]/','', html_entity_decode($data));
}
I hope you can help.
Thanks in advance
If you only need to store the amount itself inside the database and not the euro-sign, you should strip the Euro-sign before validating.
You can do this inside the beforeValidate() callback of your model;
public function beforeValidate(array $options = array())
{
if (!empty($this->data[$this->alias]['FIELDNAME']) {
// Strip the euro-sign
// NOTE: should also take plain, non-entity € into account here?
$this->data[$this->alias]['FIELDNAME'] = str_replace(
'€', '', $this->data[$this->alias]['FIELDNAME']
);
}
return parent::beforeValidate($options);
}
(Of course, replace FIELDNAME with the actual fieldname)
After stripping the currency-symbol, validate the value using the decimal or numeric validation rule
note
If you do want to store the value including the currency-symbol, use the core money validation rule.
I have a bunch of name/email fields in my form like this:
data[Friend][0][name]
data[Friend][1][name]
data[Friend][2][name]
etc.
and
data[Friend][0][email]
data[Friend][1][email]
data[Friend][2][email]
etc.
I have a custom validation rule on each one that checks to see if the corresponding field is filled in. Ie. if data[Friend][2][name] then data[Friend][2][email] MUST be filled in.
FYI, heres what one of the two rules look like:
My form validation rule: ( I have an email validation too but that's irrelevant here)
'name' => array(
'checkEmail' => array(
'rule' => 'hasEmail',
'message' => 'You must fill in the name field',
'last' => true
)
)
My custom rule code:
function hasEmail($data){
$name = array_values($data);
$name = $name[0];
if(strlen($name) == 0){
return empty($this->data['Friend']['email']);
}
return true;
}
I need to make it so that one of the pairs should be filled in as a minimum. It can be any as long as the indexes correspond.
I can't figure a way, as if I set the form rule to be required or allowEmpty false, it fails on ALL empty fields. How can I check for the existence of 1 pair and if present, carry on?
Also, I need to strip out all of the remaining empty [Friend] fields, so my saveAll() doesn't save a load of empty rows, but I think I can handle that part using extract in my controller. The main problem is this validation. Thanks.
I would have a look at the Model::beforeValidate callback (API).
Using this callback to output debug information should help you figure out how many times it fires and what data is available to the model on each call.
With this information, you could then create a flag when you find your first matching pair, and tamper with either the Model::validates array or the Model::data array to bypass subsequent validation attempts.
As for your last point, you may be able to use Set::filter to easily remove blank fields from your data set.