ElementAddCommand.class.php
3.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
/**
* Created by JetBrains PhpStorm.
* User: mnr
* Date: 28.10.14
* Time: 13:28
* To change this template use File | Settings | File Templates.
*/
namespace Cpeople\Classes\Forms\Commands;
use Cpeople\Classes\Forms\Command;
use Cpeople\Classes\Forms\Form;
class ElementAddCommand extends Command
{
private $iBlockId;
private $elementName;
private $fieldsUppercase;
private $bitrixFields;
/**
* @var Form
*/
private $form;
public function execute(Form $form)
{
$this->form = $form;
$properties = $this->getPreparedProperties();
$id = $this->addElement($properties);
$form->setDataItem('ID', $id);
}
public function __construct($isCritical, $iBlockId, $elementName = NULL, $fieldsUppercase = TRUE, Array $bitrixFields = array())
{
parent::__construct($isCritical);
$this->iBlockId = $iBlockId;
$this->elementName = $elementName;
$this->fieldsUppercase = $fieldsUppercase;
$this->bitrixFields = $bitrixFields;
}
public function getPreparedProperties()
{
$data = $this->form->getData();
$elementsProperties = array();
if($this->fieldsUppercase)
{
$data = array_change_key_case($data, CASE_UPPER);
$files = array_change_key_case($_FILES, CASE_UPPER);
}
foreach (cp_get_ib_properties($this->iBlockId) as $key => $property)
{
$elementsProperties[$property['ID']] = $data[$key];
if ($property['PROPERTY_TYPE'] == 'S')
{
$elementsProperties[$property['ID']] = ($property['USER_TYPE'] == 'HTML')
? array('VALUE' => array('TEXT' => $data[$key], 'TYPE' => 'TEXT'))
: $data[$key];
}
else if ($property['PROPERTY_TYPE'] == 'F')
{
if($property['MULTIPLE'] == 'Y')
{
for($i = 0; $i < count($files[$key]['name']); $i++)
{
$elementsProperties[$property['ID']]['n' . $i] = array(
'name' => $files[$key]['name'][$i],
'size' => $files[$key]['size'][$i],
'type' => $files[$key]['type'][$i],
'tmp_name' => $files[$key]['tmp_name'][$i]
);
}
}
else
{
$elementsProperties[$property['ID']] = $files[$key];
}
}
}
return $elementsProperties;
}
public function addElement($elementsProperties)
{
if(empty($this->elementName))
{
$this->elementName = date('Y.m.d H:i');
}
$el = new \CIBlockElement;
$props = array(
'IBLOCK_ID' => $this->iBlockId,
'PROPERTY_VALUES' => $elementsProperties,
'NAME' => $this->elementName,
"DATE_ACTIVE_FROM" => ConvertTimeStamp(time(), "FULL")
);
foreach($this->bitrixFields as $keyField => $valField)
{
$props[$keyField] = $valField;
}
$id = $el->Add($props);
if (!$id)
{
if($this->isCritical)
{
throw new \Exception($el->LAST_ERROR);
}
else
{
$this->form->setErrors($this->getErrorMessage($el->LAST_ERROR));
}
}
return $id;
}
}