{"id":13427984,"url":"https://github.com/nathanvda/cocoon","last_synced_at":"2025-05-13T17:04:49.564Z","repository":{"id":41095039,"uuid":"1347323","full_name":"nathanvda/cocoon","owner":"nathanvda","description":"Dynamic nested forms using jQuery made easy; works with formtastic, simple_form or default forms","archived":false,"fork":false,"pushed_at":"2023-08-08T14:11:26.000Z","size":375,"stargazers_count":3086,"open_issues_count":34,"forks_count":383,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-04-24T00:41:05.325Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://github.com/nathanvda/cocoon","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nathanvda.png","metadata":{"files":{"readme":"README.markdown","changelog":"History.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2011-02-09T17:50:09.000Z","updated_at":"2025-04-03T22:09:18.000Z","dependencies_parsed_at":"2022-07-21T04:39:05.225Z","dependency_job_id":"c1468c42-f05b-475e-b4ac-e22f93255571","html_url":"https://github.com/nathanvda/cocoon","commit_stats":{"total_commits":298,"total_committers":71,"mean_commits":4.197183098591549,"dds":0.3825503355704698,"last_synced_commit":"b3f4e6d1920937063cba2a4472dc4508bbac00f3"},"previous_names":[],"tags_count":43,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nathanvda%2Fcocoon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nathanvda%2Fcocoon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nathanvda%2Fcocoon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nathanvda%2Fcocoon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nathanvda","download_url":"https://codeload.github.com/nathanvda/cocoon/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253990460,"owners_count":21995774,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T01:00:43.931Z","updated_at":"2025-05-13T17:04:49.543Z","avatar_url":"https://github.com/nathanvda.png","language":"Ruby","readme":"# cocoon\n\n[![Build Status](https://travis-ci.org/nathanvda/cocoon.png?branch=master)](https://travis-ci.org/nathanvda/cocoon)\n\nCocoon makes it easier to handle nested forms.\n\nNested forms are forms that handle nested models and attributes in one form;\ne.g. a project with its tasks or an invoice with its line items.\n\nCocoon is form builder-agnostic, so it works with standard Rails, [Formtastic](https://github.com/justinfrench/formtastic), or [SimpleForm](https://github.com/plataformatec/simple_form).\nIt is compatible with rails 3, 4 and 5.\n\nThis project is not related to [Apache Cocoon](http://cocoon.apache.org/).\n\n## Prerequisites\n\nThis gem depends on jQuery, so it's most useful in a Rails project where you are already using jQuery.\nFurthermore, I would advise you to use either [Formtastic](https://github.com/justinfrench/formtastic) or [SimpleForm](https://github.com/plataformatec/simple_form).\n\n## Installation\n\nInside your `Gemfile` add the following:\n\n```ruby\ngem \"cocoon\"\n```\n\n\u003e Please note that for rails 4 you will need at least v1.2.0 or later.\n\n### Rails 6/Webpacker \n\nAdd the companion package\n\n    yarn add @nathanvda/cocoon \n    \nand then in your `app/javascripts/packs/application.js` you should add\n\n    require(\"jquery\")\n    require(\"@nathanvda/cocoon\")\n\n\n\u003e Note: there are alternative npm packages, which might better suit your needs. \nE.g. some offer the cocoon functionality without using jquery (search for `cocoon + vanilla` --I found three packages on npm already). \nObviously you are free to use those, however the code samples in this README will (still) rely on jquery.\n \n\n### Rails 3.1+/Rails 4/Rails 5\n\nAdd the following to `application.js` so it compiles to the asset pipeline:\n\n```ruby\n//= require cocoon\n```\n\n### Rails 3.0.x\n\nIf you are using Rails 3.0.x, you need to run the installation task (since rails 3.1 this is no longer needed):\n\n```bash\nrails g cocoon:install\n```\n\nThis will install the Cocoon JavaScript file. In your application layout, add the following below the default javascripts:\n\n```haml\n= javascript_include_tag :cocoon\n```\n\n## Basic Usage\n\nSuppose you have a `Project` model:\n\n```bash\nrails g scaffold Project name:string description:string\n```\n\nAnd a project has many `tasks`:\n\n```bash\nrails g model Task description:string done:boolean project:belongs_to\n```\n\nYour models are associated like this:\n\n```ruby\nclass Project \u003c ActiveRecord::Base\n  has_many :tasks, inverse_of: :project\n  accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true\nend\n\nclass Task \u003c ActiveRecord::Base\n  belongs_to :project\nend\n```\n\n\u003e *Rails 5 Note*: since rails 5 a `belongs_to` relation is by default required. While this absolutely makes sense, this also means\n\u003e associations have to be declared more explicitly. \n\u003e When saving nested items, theoretically the parent is not yet saved on validation, so rails needs help to know\n\u003e the link between relations. There are two ways: either declare the `belongs_to` as `optional: false`, but the\n\u003e cleanest way is to specify the `inverse_of:` on the `has_many`. That is why we write : `has_many :tasks, inverse_of: :project` \n \n \n\nNow we want a project form where we can add and remove tasks dynamically.\nTo do this, we need the fields for a new or existing `task` to be defined in a partial\nnamed `_task_fields.html`.\n\n### Strong Parameters Gotcha\n\nTo destroy nested models, rails uses a virtual attribute called `_destroy`.\nWhen `_destroy` is set, the nested model will be deleted. If the record is persisted, rails performs `id` field lookup to destroy the real record, so if `id` wasn't specified, it will treat current set of parameters like a parameters for a new record.\n\nWhen using strong parameters (default in rails 4), you need to explicitly\nadd both `:id` and `:_destroy` to the list of permitted parameters.\n\nE.g. in your `ProjectsController`:\n\n```ruby\n  def project_params\n    params.require(:project).permit(:name, :description, tasks_attributes: [:id, :description, :done, :_destroy])\n  end\n```\n\n### Has One Gotcha\n\nIf you have a `has_one` association, then you (probably) need to set `force_non_association_create: true` on `link_to_add_association`\n\nIf you don't do this, then rails will automatically delete your existing association when you view the edit form!\n\nMore details in the [wiki](https://github.com/nathanvda/cocoon/wiki/has_one-association)\n\n## Examples\n\nCocoon's default configuration requires `link_to_add_association` and associated partials to\nbe properly wrapped with elements. The examples below illustrate simple layouts.\n\nPlease note these examples rely on the `haml` gem ([click here](https://github.com/nathanvda/cocoon/wiki/ERB-examples) for the default `erb` views).\n\n### Formtastic\n\nIn our `projects/_form` partial we'd write:\n\n```haml\n= semantic_form_for @project do |f|\n  = f.inputs do\n    = f.input :name\n    = f.input :description\n    %h3 Tasks\n    #tasks\n      = f.semantic_fields_for :tasks do |task|\n        = render 'task_fields', f: task\n      .links\n        = link_to_add_association 'add task', f, :tasks\n    = f.actions do\n      = f.action :submit\n```\n\nAnd in our `_task_fields` partial we'd write:\n\n```haml\n.nested-fields\n  = f.inputs do\n    = f.input :description\n    = f.input :done, as: :boolean\n    = link_to_remove_association \"remove task\", f\n```\n\nThe example project [cocoon_formtastic_demo](https://github.com/nathanvda/cocoon_formtastic_demo) demonstrates this.\n\n### SimpleForm\n\nIn our `projects/_form` partial we'd write:\n\n```haml\n= simple_form_for @project do |f|\n  = f.input :name\n  = f.input :description\n  %h3 Tasks\n  #tasks\n    = f.simple_fields_for :tasks do |task|\n      = render 'task_fields', f: task\n    .links\n      = link_to_add_association 'add task', f, :tasks\n  = f.submit\n```\n\nIn our `_task_fields` partial we write:\n\n```haml\n.nested-fields\n  = f.input :description\n  = f.input :done, as: :boolean\n  = link_to_remove_association \"remove task\", f\n```\n\nThe example project [cocoon_simple_form_demo](https://github.com/nathanvda/cocoon_simple_form_demo) demonstrates this.\n\n### Standard Rails forms\n\nIn our `projects/_form` partial we'd write:\n\n```haml\n= form_for @project do |f|\n  .field\n    = f.label :name\n    %br\n    = f.text_field :name\n  .field\n    = f.label :description\n    %br\n    = f.text_field :description\n  %h3 Tasks\n  #tasks\n    = f.fields_for :tasks do |task|\n      = render 'task_fields', f: task\n    .links\n      = link_to_add_association 'add task', f, :tasks\n  = f.submit\n```\n\nIn our `_task_fields` partial we'd write:\n\n```haml\n.nested-fields\n  .field\n    = f.label :description\n    %br\n    = f.text_field :description\n  .field\n    = f.check_box :done\n    = f.label :done\n  = link_to_remove_association \"remove task\", f\n```\n\n## How it works\n\nCocoon defines two helper functions:\n\n### link_to_add_association\n\nThis function adds a link to your markup that, when clicked, dynamically adds a new partial form for the given association.\nThis should be called within the form builder.\n\n`link_to_add_association` takes four parameters:\n\n- **name**: the text to show in the link\n- **f**: the form builder\n- **association**: the name of the association (plural) of which a new instance needs to be added (symbol or string).\n- **html_options**: extra html-options (see [`link_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)\n  There are some special options, the first three allow to control the placement of the new link-data:\n  - `data-association-insertion-traversal` : the jquery traversal method to allow node selection relative to the link. `closest`, `next`, `children`, etc. Default: absolute selection\n  - `data-association-insertion-node` : the jquery selector of the node as string, or a function that takes the `link_to_add_association` node as the parameter and returns a node. Default: parent node\n  - `data-association-insertion-method` : jquery method that inserts the new data. `before`, `after`, `append`, `prepend`, etc. Default: `before`\n  - `data-association-insertion-position` : old method specifying where to insert new data.\n      - this setting still works but `data-association-insertion-method` takes precedence. may be removed in a future version.\n  - `partial`: explicitly declare the name of the partial that will be used\n  - `render_options` : options passed through to the form-builder function (e.g. `simple_fields_for`, `semantic_fields_for` or `fields_for`).\n                       If it contains a `:locals` option containing a hash, that is handed to the partial.\n  - `wrap_object` : a proc that will allow to wrap your object, especially useful if you are using decorators (e.g. draper). See example lower.\n  - `force_non_association_create`: if true, it will _not_ create the new object using the association (see lower)\n  - `form_name` : the name of the form parameter in your nested partial. By default this is `f`.\n  - `count` : the number of nested items to insert at once. Default `1`.\n\nOptionally, you can omit the name and supply a block that is captured to render the link body (if you want to do something more complicated).\n\n#### :render_options\nInside the `html_options` you can add an option `:render_options`, and the containing hash will be handed down to the form builder for the inserted\nform.\n\nWhen using Twitter Bootstrap and SimpleForm together, `simple_fields_for` needs the option `wrapper: 'inline'` which can\nbe handed down as follows:\n\n(Note: In certain newer versions of simple_form, the option to use is `wrapper: 'bootstrap'`.)\n\n```haml\n= link_to_add_association 'add something', f, :something,\n    render_options: { wrapper: 'inline' }\n```\n\nTo specify locals that needed to handed down to the partial:\n\n```haml\n= link_to_add_association 'add something', f, :something,\n    render_options: {locals: { sherlock: 'Holmes' }}\n```\n\n#### :partial\n\nTo override the default partial name, e.g. because it shared between multiple views:\n\n```haml\n= link_to_add_association 'add something', f, :something,\n    partial: 'shared/something_fields'\n```\n\n#### :wrap_object\n\nIf you are using decorators, the normal instantiation of the associated object will not be enough. You actually want to generate the decorated object.\n\nA simple decorator would look like:\n\n```ruby\nclass CommentDecorator\n  def initialize(comment)\n    @comment = comment\n  end\n\n  def formatted_created_at\n    @comment.created_at.to_formatted_s(:short)\n  end\n\n  def method_missing(method_sym, *args)\n    if @comment.respond_to?(method_sym)\n      @comment.send(method_sym, *args)\n    else\n      super\n    end\n  end\nend\n```\n\nTo use this:\n\n```haml\n= link_to_add_association('add something', @form_obj, :comments,\n    wrap_object: Proc.new {|comment| CommentDecorator.new(comment) })\n```\n\nNote that the `:wrap_object` expects an object that is _callable_, so any `Proc` will do. So you could as well use it to do some fancy extra initialisation (if needed).\nBut note you will have to return the (nested) object you want used.\nE.g.\n\n\n```haml\n= link_to_add_association('add something', @form_obj, :comments,\n    wrap_object: Proc.new { |comment| comment.name = current_user.name; comment })\n```\n\n#### :force_non_association_create\n\nIn normal cases we create a new nested object using the association relation itself. This is the cleanest way to create\na new nested object.\n\nThis used to have a side-effect: for each call of `link_to_add_association` a new element was added to the association.\nThis is no longer the case.\n\nFor backward compatibility we keep this option for now. Or if for some specific reason you would really need an object\nto be _not_ created on the association, for example if you did not want `after_add` callback to be triggered on\nthe association.\n\nExample use:\n\n```haml\n= link_to_add_association('add something', @form_obj, :comments,\n    force_non_association_create: true)\n```\n\nBy default `:force_non_association_create` is `false`.\n\n### link_to_remove_association\n\nThis function will add a link to your markup that, when clicked, dynamically removes the surrounding partial form.\nThis should be placed inside the partial `_\u003cassociation-object-singular\u003e_fields`.\n\nIt takes three parameters:\n\n- **name**: the text to show in the link\n- **f**: referring to the containing form-object\n- **html_options**: extra html-options (see `link_to`)\n\nOptionally you could also leave out the name and supply a block that is captured to give the name (if you want to do something more complicated).\n\nOptionally, you can add an html option called `wrapper_class` to use a different wrapper div instead of `.nested-fields`.\nThe class should be added without a preceding dot (`.`).\n\n\u003e Note: the javascript behind the generated link relies on the presence of a wrapper class (default `.nested-fields`) to function correctly.\n\nExample:\n```haml\n= link_to_remove_association('remove this', @form_obj,\n  { wrapper_class: 'my-wrapper-class' })\n```\n\n### Callbacks (upon insert and remove of items)\n\nOn insertion or removal the following events are triggered:\n\n* `cocoon:before-insert`: called before inserting a new nested child, can be [canceled](#canceling-a-callback)\n* `cocoon:after-insert`: called after inserting\n* `cocoon:before-remove`: called before removing the nested child, can be [canceled](#canceling-a-callback)\n* `cocoon:after-remove`: called after removal\n\nTo listen to the events in your JavaScript:\n\n```javascript\n  $('#container').on('cocoon:before-insert', function(e, insertedItem, originalEvent) {\n    // ... do something\n  });\n```\n\n...where `e` is the event and the second parameter is the inserted or removed item. This allows you to change markup, or\nadd effects/animations (see example below).\n`originalEvent` is also passed and references the event that triggered an insertion or removal (e.g. the `click` event on the link to add an association)\n\n\nIf in your view you have the following snippet to select an `owner`:\n\n```haml\n#owner\n  #owner_from_list\n    = f.association :owner, collection: Person.all(order: 'name'), prompt: 'Choose an existing owner'\n  = link_to_add_association 'add a new person as owner', f, :owner\n```\n\nThis will either let you select an owner from the list of persons, or show the fields to add a new person as owner.\n\nThe callbacks can be added as follows:\n\n```javascript\n$(document).ready(function() {\n    $('#owner')\n      .on('cocoon:before-insert', function() {\n        $(\"#owner_from_list\").hide();\n        $(\"#owner a.add_fields\").hide();\n      })\n      .on('cocoon:after-insert', function() {\n        /* ... do something ... */\n      })\n      .on(\"cocoon:before-remove\", function() {\n        $(\"#owner_from_list\").show();\n        $(\"#owner a.add_fields\").show();\n      })\n      .on(\"cocoon:after-remove\", function() {\n        /* e.g. recalculate order of child items */\n      });\n\n    // example showing manipulating the inserted/removed item\n\n    $('#tasks')\n      .on('cocoon:before-insert', function(e,task_to_be_added) {\n        task_to_be_added.fadeIn('slow');\n      })\n      .on('cocoon:after-insert', function(e, added_task) {\n        // e.g. set the background of inserted task\n        added_task.css(\"background\",\"red\");\n      })\n      .on('cocoon:before-remove', function(e, task) {\n        // allow some time for the animation to complete\n        $(this).data('remove-timeout', 1000);\n        task.fadeOut('slow');\n      });\n});\n```\n\nNote that for the callbacks to work there has to be a surrounding container to which you can bind the callbacks.\n\nWhen adding animations and effects to make the removal of items more interesting, you will also have to provide a timeout.\nThis is accomplished by the following line:\n\n```javascript\n$(this).data('remove-timeout', 1000);\n```\n\nYou could also immediately add this to your view, on the `.nested-fields` container (or the `wrapper_class` element you are using).\n\n#### Canceling a Callback\n\nYou can cancel an action from occurring, either an insertion or removal, within the `before-\u003caction\u003e` callback by calling `event.preventDefault()` anywhere within the callback.\n\nFor example:\n\n```javascript\n  $('#container').on('cocoon:before-insert', function(event, insertedItem) {\n    var confirmation = confirm(\"Are you sure?\");\n    if( confirmation === false ){\n      event.preventDefault();\n    }\n  });\n```\n\n### Control the Insertion Behaviour\n\nThe default insertion location is at the back of the current container. But we have added two `data-` attributes that are read to determine the insertion-node and -method.\n\nFor example:\n\n```javascript\n$(document).ready(function() {\n    $(\"#owner a.add_fields\").\n      data(\"association-insertion-method\", 'before').\n      data(\"association-insertion-node\", 'this');\n});\n```\n\nThe `association-insertion-node` will determine where to add it. You can choose any selector here, or specify this. Also, you can pass a function that returns an arbitrary node. The default is the parent-container, if you don't specify anything.\n\nThe `association-insertion-method` will determine where to add it in relation with the node. Any jQuery DOM Manipulation method can be set but we recommend sticking to any of the following: `before`, `after`, `append`, `prepend`. It is unknown at this time what others would do.\n\nThe `association-insertion-traversal` will allow node selection to be relative to the link. \n\nFor example:\n\n```javascript\n$(document).ready(function() {\n    $(\"#owner a.add_fields\").\n      data(\"association-insertion-method\", 'append').\n      data(\"association-insertion-traversal\", 'closest').\n      data(\"association-insertion-node\", '#parent_table');\n});\n```\n\n(if you pass `association-insertion-node` as a function, this value will be ignored)\n\n\nNote, if you want to add templates to the specific location which is:\n\n- not a direct parent or sibling of the link\n- the link appears multiple times - for instance, inside a deeply nested form\n\nyou need to specify `association-insertion-node` as a function.\n\n\nFor example, suppose Task has many SubTasks in the [Example](#examples), and have subtask forms like the following.\n\n```haml\n.row\n  .col-lg-12\n    .add_sub_task= link_to_add_association 'add a new sub task', f, :sub_tasks\n.row\n  .col-lg-12\n    .sub_tasks_form\n      fields_for :sub_tasks do |sub_task_form|\n        = render 'sub_task_fields', f: sub_task_form\n```\n\nThen this will do the thing.\n\n```javascript\n$(document).ready(function() {\n    $(\".add_sub_task a\").\n      data(\"association-insertion-method\", 'append').\n      data(\"association-insertion-node\", function(link){\n        return link.closest('.row').next('.row').find('.sub_tasks_form')\n      });\n});\n```\n\n\n### Partial\n\nIf no explicit partial name is given, `cocoon` looks for a file named `_\u003cassociation-object_singular\u003e_fields`.\nTo override the default partial use the `:partial` option.\n\nFor the JavaScript to behave correctly, the partial should start with a container (e.g. `div`) of class `.nested-fields`, or a class of your choice which you can define in the `link_to_remove_association` method.\n\nThere is no limit to the amount of nesting, though.\n\n## I18n\n\nAs you seen in previous sections, the helper method `link_to_add_association` treats the first parameter as a name. Additionally, if it's skipped and the `form` object is passed as the first one, then **Cocoon** names it using **I18n**.\n\nIt allows to invoke helper methods like this:\n\n```haml\n= link_to_add_association form_object, :tasks\n= link_to_remove_association form_object\n```\n\ninstead of:\n\n```haml\n= link_to_add_association \"Add task\", form_object, :tasks\n= link_to_remove_association \"remove task\", form_object\n```\n\n**Cocoon** uses the name of `association` as a translations scope key. If custom translations for association is not present it fallbacks to default name. Example of translations tree:\n\n```yaml\nen:\n  cocoon:\n    defaults:\n      add: \"Add record\"\n      remove: \"Remove record\"\n    tasks:\n      add: \"Add new task\"\n      remove: \"Remove old task\"\n```\n\nNote that `link_to_remove_association` does not require `association` name as an argument. In order to get correct translation key, **Cocoon** tableizes `class` name of the target object of form builder (`form_object.object` from previous example).\n\n## Note on Patches/Pull Requests\n\n* Fork the project.\n* Make your feature addition or bug fix.\n* Add tests for it. This is important so I don't break it in a\n  future version unintentionally.\n* Commit, do not mess with rakefile, version, or history.\n  (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)\n* Send me a pull request. Bonus points for topic branches.\n\n\n## Contributors\n\nThe list of contributors just keeps on growing. [Check it out!](https://github.com/nathanvda/cocoon/graphs/contributors)\nI would really really like to thank all of them. They make cocoon more awesome every day. Thanks.\n\n## Todo\n\n* add more sample relations: `has_many :through`, `belongs_to`, ...\n* improve the tests (test the javascript too)(if anybody wants to lend a hand ...?)\n\n## Copyright\n\nCopyright (c) 2010 Nathan Van der Auwera. See LICENSE for details.\n\n## Not Related To Apache Cocoon\n\nPlease note that this project is not related to the Apache Cocoon web framework project.\n\n[Apache Cocoon](http://cocoon.apache.org/), Cocoon, and Apache are either registered trademarks or trademarks of the [Apache Software Foundation](http://www.apache.org/) in the United States and/or other countries.\n","funding_links":[],"categories":["View Helper","HTML \u0026 Markup","Ruby","Form Builder","视图"],"sub_categories":["Omniauth","Form Builders"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnathanvda%2Fcocoon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnathanvda%2Fcocoon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnathanvda%2Fcocoon/lists"}