1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11: use Nette\Http\FileUpload;
12:
13:
14: /**
15: * Text box and browse button that allow users to select a file to upload to the server.
16: */
17: class UploadControl extends BaseControl
18: {
19:
20: /**
21: * @param string label
22: * @param bool allows to upload multiple files
23: */
24: public function __construct($label = NULL, $multiple = FALSE)
25: {
26: parent::__construct($label);
27: $this->control->type = 'file';
28: $this->control->multiple = (bool) $multiple;
29: }
30:
31:
32: /**
33: * This method will be called when the component (or component's parent)
34: * becomes attached to a monitored object. Do not call this method yourself.
35: * @param Nette\ComponentModel\IComponent
36: * @return void
37: */
38: protected function attached($form)
39: {
40: if ($form instanceof Nette\Forms\Form) {
41: if ($form->getMethod() !== Nette\Forms\Form::POST) {
42: throw new Nette\InvalidStateException('File upload requires method POST.');
43: }
44: $form->getElementPrototype()->enctype = 'multipart/form-data';
45: }
46: parent::attached($form);
47: }
48:
49:
50: /**
51: * Loads HTTP data.
52: * @return void
53: */
54: public function loadHttpData()
55: {
56: $this->value = $this->getHttpData(Nette\Forms\Form::DATA_FILE);
57: if ($this->value === NULL) {
58: $this->value = new FileUpload(NULL);
59: }
60: }
61:
62:
63: /**
64: * Returns HTML name of control.
65: * @return string
66: */
67: public function getHtmlName()
68: {
69: return parent::getHtmlName() . ($this->control->multiple ? '[]' : '');
70: }
71:
72:
73: /**
74: * @return static
75: * @internal
76: */
77: public function setValue($value)
78: {
79: return $this;
80: }
81:
82:
83: /**
84: * Has been any file uploaded?
85: * @return bool
86: */
87: public function isFilled()
88: {
89: return $this->value instanceof FileUpload ? $this->value->isOk() : (bool) $this->value; // ignore NULL object
90: }
91:
92:
93: /**
94: * Have been all files succesfully uploaded?
95: * @return bool
96: */
97: public function isOk()
98: {
99: return $this->value instanceof FileUpload
100: ? $this->value->isOk()
101: : $this->value && array_reduce($this->value, function ($carry, $fileUpload) {
102: return $carry && $fileUpload->isOk();
103: }, TRUE);
104: }
105:
106: }
107: