-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Default values for fields? #58
Comments
You can do this by setting a default attribute to your model, but yeah I think there should be a way to pass a value to the fields. |
This would be especially useful for the code field. Being able to provide placeholder JSON data into a field by default would allow for more context on how that field can be filled appropriately, rather than being constricted to having it filled with "null" as it currently does. |
@mink Currently I hide my code field's when creating a record and use a model observer to input the default json values. Not the best solution but it does the job. |
I've found that if you set the default attribute on a model (as @chinleung mentioned) as an array, it will fill a JSON code field on the new resource view. If you set the default value as a string, any code field that is not declared as JSON will be filled in with the specified value too. Other fields that I've tested such as the Text field will accept various types as a default value to fill in the field. This would be great to have in the documentation. It is personally enough of a solution for my usage, however, being able to set default values within the resource class would be useful as well. Edit: If you override a model's constructor you can programmatically declare the default attribute values, which you could use to pull in config data for instance. If you require different default values for the model specifically in Nova you could assign the values this way as well. |
Is there a way to do this for an action field? I have an action field asking me to input something, it would be great if it would fill a field for me with a default data. Something like:
|
Would be great to be able to default let's say a |
Something is known, how can I set a default value? |
As per what @mink suggested, default values for json (code) fields can be achieved by setting the value to the attribute in the model's constructor
This works for me: protected $casts = [
'fields' => 'array',
];
public function __construct(array $attributes = [])
{
$this->fields = config('app.default_fields');
parent::__construct($attributes);
} I do however also have this field on a pivot... and haven't found a way to specify a default for that... the best way would probably indeed by a |
@MadMikeyB You can achieve set the authenticated user by default for the BelongsTo::make('User') field like this:
|
Yeah but this seems like a hacky way to do it. Taylor explicitly said "Nova doesn't interact with your code, it doesn't even touch your code at all". I don't want to make adjustments to my code, especially overriding a constructor of a model, just so I can set default value in Nova. IMHO, this should be resolved, especially since this doesn't feel like a hard bug to fix, since there is a Until then, I'm fine with overriding certain methods in Nova resources, or extending the base Resource class or something, but I'm not fine with modifying my models, especially setting default attributes with some hardcoded values. |
Your point is valid, I was already setting this default in the creating
block, for other code paths, it was just a case of making it happen earlier
so it applies to an unsaved model e.g. the nova create forms — nova should
have specific defaultValue handling also, so that changes aren’t necessary,
and for when the defaults need to be different for the admin
…On Thu, 30 Aug 2018 at 15:08, Josip Crnković ***@***.***> wrote:
Yeah but this seems like a hacky way to do it. Taylor explicitly said
"Nova doesn't interact with your code, it doesn't even touch your code at
all". I don't want to make adjustments to my code, especially overriding a
constructor of a model, just so I can set default value in Nova. IMHO, this
should be resolved, especially since this doesn't feel like a hard bug to
fix, since there is a value property on the Field (or Element, not sure)
class.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#58 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AARq-8eBkVN_UDfIbPkg18KuZbB1-8xnks5uV-PlgaJpZM4WJ-2I>
.
|
This repository is for tracking bugs. Feature requests may be emailed to Nova customer support. |
Add the following to your resource file
|
This is how you set default values. Will work most of the times except when your field is a number and you want to set 0 as default then it wouldn't work.
|
How to specify meta tag only while creating a new value and not for all. Right now it ignores its own values and displays this for all the records. |
@sonalmahajan01 You can do this to have it only populate the default value if the item doesn't have a value for that field already: |
Because of new PHP syntax, it can be even easier. Text::make("Name")->withMeta(['value' => $this->name ?? 'Default']); Makes use of the Null Coalescing Operator. |
@Jam0r85 I have managed to set a default value (current user's ID) on a BelongsTo field this way:
|
@peterhaluska small note on your solution. It works great for Create/Edit. However on Index/Details pages it causes the BelongTo value to be the ID instead. I got around by adding two BelongsTo. The original BelongTo with
|
You should use this package: Nova Hidden Fields also you can set default value for your hidden fields such as current user_id and much more.. |
If you’re using the auth user for the id, don’t pass it via hidden fields. Use observers. Creating and updating events can access the auth user |
@peterhaluska great solution, you saved me lots of time!! @nickpoulos there is no need to make two BelongsTo. I am only using the 'belongsToId' and removed the 'value', it works great like that.
|
Unfortunately using the withMeta function doesn't appear to work in combination displayUsingLabels() when using a select field. Does anyone have a solution for this situation?
|
@devonmather You are not passing the options correctly. It should be:
Then the value Standard is selected by default. |
@chinleung Thanks for pointing out the syntax error I had in the arguments. However, that wasn't the issue. The issue is on the detail and index where the number '1' shows in place of the text 'Standard'. Please see screenshots. I have since solved the issue by using the model's attributes. It seems the withMeta functionality for setting defaults could be flawed in that it will always set that value for any page, not just the create form. It also does not respect the displayUsingLabels() function. |
you can use
|
I've just published a package which wraps this default behaviour in some convenience methods, including caching previous values. Hope this is useful! https://novapackages.com/packages/inspheric/nova-defaultable |
@LukasRothZeitraum, @devonmather I've come up with a solution that works for me, and it seems to solve this problem. It also accounts for the issue that @crnkovic pointed out, and thus my solution doesn't require changing anything outside of Nova. The problem that you guys were seeing is that using the Additionally, I'm dealing with a field that uses a resolve callback, which the value provided in The solution lies with provide default attributes to the model, but doing it within the Nova codebase. This is similar to solution @idragon81 posted, but more abstract. In my base resource class, I've added the following methods: /**
* Creates and returns a fresh instance of the model represented by the resource.
*
* @return mixed
*/
public static function newModel()
{
$model = static::$model;
$instance = new $model;
$instance->setRawAttributes(static::getDefaultAttributes());
return $instance;
}
/**
* Returns the default attributes for new model instances.
*
* @return array
*/
public static function getDefaultAttributes()
{
return static::$defaultAttributes ?? [];
} This allows me to provide either a Now in my specific resource, I've added the following attribute: /**
* The default attributes for new model instances.
*
* @var array
*/
public static $defaultAttributes = [
'percent' => 1
]; Doing this will send my "1" through my resolve callback, and converting it to "100" (similar to how "0.35" would have been changed to "35", had "0.35" been the value stored in the database). If the model is instead retrieved from the database, then it will replace my default value (even if the stored value is Hopefully this helps. |
I don't know if this is the Laravel way of doing things, but I just returned the default value within the resolve callback. However, I tried the same thing for relationships and it threw an error. Boolean::make('My Boolean', 'working', function () {
return true;
}) Date::make('My Default Date', 'date', function () {
return now();
}) |
For anyone interested I made this macro which seems to do the trick: In NovaServiceProvider: public function boot()
{
Field::macro('default', function ($default) {
return $this->resolveUsing(function ($value) use ($default) {
return $value ?? $default;
});
});
parent::boot();
} Use it like: Text::make('Name')
->sortable()
->rules('required', 'max:255')
->default('John Doe'), |
@rasmuscnielsen Excellent thanks a lot ! In NovaServiceProvider : public function boot()
{
Field::macro('default', function ($default) {
return $this->resolveUsing(function ($value, $model) use ($default) {
return $model->getKey() === null ? $default : $value;
});
});
parent::boot();
} And the usage stay the same when creating the field. As i'm also using, public function getKey()
{
return $this->inUseKey();
} In my layouts in order to have them working like expected. |
@rasmuscnielsen and @intraordinaire when defining a macro like that I get
at Any ideas what I am missing? |
@intraordinaire Excelent, but i dont understand where you put and how to use in contenflexible |
@mpoma i have a use Whitecube\NovaFlexibleContent\Layouts\Layout;
class BaseLayout extends Layout
{
/**
* Return the layout identifier
*
* @return null|string
*/
public function getKey()
{
return $this->inUseKey();
}
} @ajthinking Not sure what can be the problem here. Are you well in the |
Just for completeness, setting the default value via the 'value' attribute and The correct answer is indeed from #58 (comment) (and #58 (comment)) : set the default values directly on the model attributes. I personally do it in the |
did you ever figure out a way to set default values on pivot fields? i've looked up and down with no luck |
How would default value be handled for hasMany? For example on User Detail page, I click 'add book', but on the book creation form i want school_id of Book to be prefilled with that User's school_id |
I have tried something similar to your situation, in the default callback function I want to use another relation of the current model to find the ID to use as default value, but seems not to work, the callback is not even called? What I tried was something like this (in the Book fields):
So that when I create a new book from the User page, where the user ID is already fixed, it should be able to also assign the default school ID. But since it doesn't seem to work, what would be the correct way of using default to achieve this? |
It seems like the callback is simply not executed for BelongsTo fields?
This works (like in the examples):
But then this does nothing:
Another problem seems to be that at the moment of assigning the default value, the user relation is not known yet (even though we create the Book from the User resource page, and the dropdown on the Book create page is greyed out with the correct value). This means that when I try to do it like this:
I get Trying to get property 'school' of non-object So maybe using default for this is not even possible? |
Have you solved this problem? Right now, I also can't solve the problem of displaying labels when default values are set for a field
|
Easier, for the date field asked:
|
Wow this super cool soap opera is like the longest ever explanation of how to set defaults for Nova! For those still struggling with
The key is don't use Select::make('Status')->options(
Leads::ui_options()
)
->sortable()
->resolveUsing(function () {
return $this->status ?? 'new';
})
->displayUsingLabels(), Compliments of this Stack post. |
This is how to set a default value on create only for a DateTime field:
Inspired by https://vander.host/knowledgebase/software-development/how-to-set-the-default-date-using-laravel-nova/ |
I met this issue today, should use this instead of the
|
it's work, tnx |
Text::make( 'purchase_count') |
Not sure if i've missed this from the docs but is there anyway to populate a field in a create form with a default value?
eg.
This would be helpful with relationship fields also, especially with BelongsTo (example of using Spark with it's current_team_id column in the users table.
Would help reduce bits and pieces being added to model observers checking for missing values and populating them etc
The text was updated successfully, but these errors were encountered: