Problem with component “Component with name xxx does not exist”
- Tomas Jancik
- Member | 103
I want to show the username/login box on every page, so I created new
component for this and saved it in app/components. But when I try to display it
in the @layout.latte file, I get an error7
Component with name ‘loginbox’ does not exist.
Code of my component
<?php
class LoginBoxControl extends Nette\Application\UI\Control {
public function render() {
$template = $this->template;
$template->setFile(dirname(__FILE__) . '/LoginBox.phtml');
// vložíme do šablony nějaké parametry
//$template->param = $value;
// a vykreslíme ji
$template->render();
}
}
in the template there is just plain text so far..
in the #layout I'm using
{control loginbox}
I used the same way for component on my other web and there it is working
fine…
RobotLoader is scaning the whole app/ dir
I tried also deleting cache
- Tomas Jancik
- Member | 103
yes, that was the problem… But could it be done somehow without the function in Presenter? I find this quite anoying that I have to write the component and then register it again in the presenter…
- HosipLan
- Moderator | 4668
Well, but that is best practise. You still have other options, you can create some logic, that can attach the component without the method in every single presenter, but why? That would be either quite complicated or simple with security issues.
In this case, just put the component factory in BasePresenter
(and leave the component as standalone class).
- Jan Tvrdík
- Nette guru | 2595
Tomas Jancik wrote:
But could it be done somehow without the function in Presenter?
You can override createComponent
method but make sure you don't
give user the possibility to instantiate any class in your code.
DO NOT USE THIS AS IT LEADS TO SECURITY ISSUES
class FooPresenter extends BasePresenter
{
protected function createComponent($name)
{
$component = parent::createComponent($name);
if ($component === NULL && class_exists($name)) {
$component = new $name;
}
return $component;
}
}
This should be fine
/**
* @controls(loginBox)
*/
class FooPresenter extends BasePresenter
{
protected function createComponent($name)
{
$component = parent::createComponent($name);
if (!isset($component) && !isset($this->components[$name])) {
$allowedControls = (array) $this->getReflection()->getAnnotation('controls');
if (in_array($name, $allowedControls)) {
$class = $name . 'Control';
if (class_exists($class) && is_subclass_of($class, 'Nette\Application\UI\Control')) {
$component = new $class($this, $name);
}
}
}
return $component;
}
}