I have minimally changed the registration process - instead of name, I'm using firstname and lastname. No problem.
form: $.extend(true, new SparkForm({
firstname: '',
lastname: '', email: '' }),
Spark.forms.updateContactInformation)
That works fine for CREATION of the user object, however upon successful registration, I want the user to fill in the rest of their profile - of which there are many new fields I'm adding.
So, in adding all the new fields to the settings page (for example, lastname), on clicking the update button, it seems something is still validating the name, instead of firstname, and I'm unsure where to put in my new fields for validation purposes.
Getting error The name field is required.
As per the docs, I'm using Spark::validateUsersWith to validate the firstname instead of name, hence the create user works - but where is the validation for updating ? I cant seem to locate that.
I can see its using ContactInformationController#update and confirm its being hit with some logging, however even trying explicitly
$this->validate($request, [
'lastname' => 'nullable|max:255',
]);
in there doesn't do the trick - must be something in here but not sure how it works:
$this->interaction(
$request, UpdateContactInformation::class,
[$request->user(), $request->all()]
);
Related
I'm really confused about why this is happening? I had successfully added a record then when I tried to update the record It says that the field is required even I passing it already. Then when I tried to add "sometimes" on the validation. Now, it works. Why? Please enlighten me. Thank you!
my Test Model
This was the result when I tried to remove "sometimes"
As per the doc sometimes is used for :
Validating When Present In some situations, you may wish to run
validation checks against a field only if that field is present in the
input array. To quickly accomplish this, add the sometimes rule to
your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email', ]);
Therefore since the request is not containing the expected fields, the validation is successful
Adding sometimes effectively disables the required rule and allows the client to simply not pass that field into the input.
In your case, the validator is probably not receiving the correct data from input. Because If it did, the required rule would act correctly.
Please post the code of your validator to be able to debug the problem.
sometimes is when you sometimes include the field.
Let's see an example of validation when creating a user:-
$validation = [
"name" => "required|string|",
"email" => "required|email",
"hobbies" => "sometimes|array"
];
Sample payloads
{
name: "Bob",
email: "bob#gmail.com"
}
// this will pass
{
name: "Bob",
email: "bob#gmail.com",
hobbies: ["fishing", "swimming"]
}
// this would also pass
{
name: "Bob",
email: "bob#gmail.com",
hobbies: "swimming"
}
// this would fail since it doesn't match "array" validation
I want to set the default value of a resource field to the authenticated user's id. I have a model called Note which has a one to many relationship with Game and User.
User hasMany Note
Game hasMany Note
Note belongsTo User
Note belongsTo Game
In Laravel Nova my fields looks like this for the note
ID::make()->sortable(),
Text::make('Note', 'note')->onlyOnIndex(),
Textarea::make('Note', 'note')->alwaysShow(),
BelongsTo::make('Game', 'game')->hideWhenCreating()->hideWhenUpdating(),
BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating(),
DateTime::make('Created At', 'created_at')->hideWhenCreating(),
DateTime::make('Updated At', 'updated_at')->hideWhenCreating(),
Because I am referencing the Note on the Game Nova resource, when I create a Note, the game_id column is populated correctly. But, I want the user_id column to be the value of the authenticated user. It does not seem to work like this, how would I accomplish it?
If I understand correctly from the line BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating() you're trying to set a default value for the column without showing the field on the form?
I don't think this is possible in this way. As soon as you use the hide functions the fields aren't rendered and will never be passed along with the request. I tried this, and the user_id field was never sent with the request.
I think there are two ways to do this:
Show the field in the form and set the default value using the metadata (and perhaps making the field read-only for good measure).
BelongsTo::make('Created By', 'user', 'App\Nova\User')->withMeta([
"belongsToId" => auth()->user()->id,
])
See this part of the Nova docs
Or use the Eloquent creating event. The following will go in your Note model.
public static function boot()
{
parent::boot();
static::creating(function($note)
{
$note->user_id = auth()->user()->id;
});
}
Granted, the above method is a bit simple. You'd be better off using proper event listeners.
Sidenote: from an architectural point of view, I'd go with option 2. Setting a default value without getting the end-user involved sounds like a job for the Eloquent model, not for a Nova form.
You can use a method resolveUsing(). An example
<?php
//...
Select::make('My Select', 'my_custom_name')
->options(['a' => 'a', 'b' => 'b', 'c' => 'c'])
->resolveUsing(function ($value, $resource, $attribute) {
// $value = model attribute value
// $attribute = 'my_custom_name'
return 'b';
});
I have the following database structure:
Enquiries
id
total_widgets
total_amount
customer_id
Customers
id,
first_name,
last_name
Using the form when you are creating an Enquiry you can enter the Customers details into the section and this will store using firstOrCreate and then get the id in order to link to Enquiry to the Customer
Now, the issue is that this is all done inside the store method within the Customers controller, like the following:
public function store(Request $request)
{
$rules = array(
"first_name" => "required",
"last_name" => "required",
"total_widgets" => "required"
);
// Handle validation
// Create customer
$customer = \App\Customers::firstOrCreate(['first_name' => $request-
>get('first_name')]);
$enquiry = new \App\Enquiries();
$enquiry->customer_id = $customer->id;
$enquiry->save();
}
The issue with doing it like this is that it's not separated out and that if the process of creating a customer changes, then I would need to change this a lot of times. (Everytime I have a section which requires a customer)..
Is there a better way to do this? For example, should the customer be created separately and then the id is passed into the $request?
Another way of doing this is :
1) In Enquiries form add button called "add new customer".
2) When you click on this button a modal will appear and then fill details click submit.
3) On clicking submit make an ajax call to Customercontroller and insert the data then return the last inserted id.
4) Now you can see the new user in drop down box(There will be some drop down for selecting the user) of enquirey form just select it and then press submit.
5) It will passed to the enquirey controller and and store it.
Hope this will help you.
I'm considering setting up some proof-of-concept tool that could grab metadata from a Symfony2 FormType instance in order to dump a validation schema as JSON, something like the following:
[
{
name: 'someFieldName',
value: '',
email: true
},
{
name: 'yetAnotherFieldName',
value: 'I have a default value',
required: true
}
]
The aim obviously is to use it in front-end JS code (let's say React), to be able to set up the same validation constraints, as much as possible (required and the likes).
However, Symfony is well-architectured and its Form component knows nothing about validation. Considering only the nominal case of a simple form to begin with, how would one go about doing it? How to map back the form to the validatable objects/entities it references?
Using the symfony validator you can get the metadata for a given class:
$this->get('validator')->getMetadataFor(Foo::class);
It returns a ClassMetadata instance. If the passed value is an entity, you will have the members and properties properties returned which then contain a constraints property with the classes being used.
Final step is to serialize that in JSON.
I am trying to validate an email address in my Customer table. There is a column in the Customer table called Brand where effectively the same email address could be registered to multiple brands for example:
Email Brand
me#mywebsite.com firstsite.com
me#mywebsite.com secondsite.com
When validating the email address I need to check the email is unique in the Customer table for the current Brand. Currently my validation rule looks like this
$rules = array('email' => 'required|email|unique:Customer,Email');
however Brand must appear in there someone to say the email must be unique to the customer for the current brand
Any help much appreciated
You can use the column and value parameter of the unique validation rule to add a condition to the rule.
'email' => 'required|email|unique:Customer,Email,null,null,column,value'
The problem is you need your Brand input in order to create your rule like this :
$rules['email'] = 'required|email|unique:Customer,Email,null,null,Brand,' . Input::get('Brand');
This rule will check if the email is unique where the brand has the given value.
More information here :
http://laravel.com/docs/validation#rule-unique
There is also a package that could help you :
https://github.com/felixkiss/uniquewith-validator
$rules = array('email' => 'required|email|unique:Customer,Email'); this will query your model for finding the entered email if the email is already present then an error message is raised. so this will not work with your app design flow. you have to run sql query to find out if the email is present with your current brand if yes return error message if not save the data. something like that
I would go for writing my own custom validation rule. Custom validation rule will be more common solution and you can name it as it suites you best. It can be created using the Validator::extend() and a closure, like this :
Validator::extend('awesome', function($field, $value, $params)
{
return $value == 'awesome';
});
or via validator class. Have a research at this topic, maybe here (scroll to custom rules section) or any other source you find.