DynamicFormBehavior.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: NODELOG
  5. * DateTime: 2016/10/27 16:51
  6. * Description:
  7. */
  8. namespace common\behaviors;
  9. use yii\base\Behavior;
  10. use yii\helpers\ArrayHelper;
  11. class DynamicFormBehavior extends Behavior
  12. {
  13. /**
  14. * ['attribute' => ['type' => 'text', 'items' => [], 'options' => []]
  15. * @var array
  16. */
  17. public $formAttributes = [];
  18. public function supportAttributeTypes()
  19. {
  20. return [
  21. 'text',
  22. 'array',
  23. 'password',
  24. 'textarea',
  25. 'select',
  26. 'checkbox',
  27. 'radio',
  28. 'image',
  29. 'images',
  30. 'editor',
  31. 'date',
  32. 'datetime',
  33. 'file',
  34. 'city'
  35. ];
  36. }
  37. public function init()
  38. {
  39. parent::init();
  40. if (empty($this->formAttributes)) {
  41. $formAttributes = $this->owner->attributes();
  42. $formAttributes = array_combine($formAttributes, $formAttributes);
  43. ArrayHelper::remove($formAttributes, $this->owner->primaryKey()[0]);
  44. $this->formAttributes = $formAttributes;
  45. }
  46. }
  47. public function getAttributeType($attribute)
  48. {
  49. if(isset($this->formAttributes[$attribute])) {
  50. if(is_string($this->formAttributes[$attribute])) {
  51. return $this->formAttributes[$attribute];
  52. } else {
  53. return ArrayHelper::getValue($this->formAttributes[$attribute], 'type', 'text');
  54. }
  55. }
  56. }
  57. public function getAttributeItems($attribute)
  58. {
  59. if(isset($this->formAttributes[$attribute])) {
  60. return ArrayHelper::getValue($this->formAttributes[$attribute], 'items', []);
  61. }
  62. }
  63. public function getAttributeOptions($attribute)
  64. {
  65. if(isset($this->formAttributes[$attribute])) {
  66. $options = ArrayHelper::getValue($this->formAttributes[$attribute], 'options', []);
  67. if (is_callable($options)) {
  68. $options = call_user_func($options, $this->owner);
  69. }
  70. return $options;
  71. }
  72. return [];
  73. }
  74. public function formAttributes()
  75. {
  76. return array_filter(array_keys($this->formAttributes), function ($value) {
  77. if (!in_array($this->getAttributeType($value), $this->supportAttributeTypes())) {
  78. return false;
  79. }
  80. return true;
  81. });
  82. }
  83. }