0

In my Symfony2.6.6 project I have a category entity. I don't know how to say that properly but use the doctrine tree extension to create a tree with the category entity like:

  • Category 1
    • Child Category 1
    • Child Category 2
  • Category 2
    • Child Category 3 ...

Now when creating the form type for creating a new Category I want to customize the array of the parent field.

The code I use

$builder->add('parent', 'entity', array('class' => 'AcmeBlogBundle:Category', 'property' => 'title'));

generates just an array with all the title as expected. But I want the array values to append a '-' for every level of the tree. Category 1 for example would be '- Category 1' and Child Category 1 would be '-- Child Category 1'. How can I do that?

Sorry if this has been asked before, I don't know how to search for that.

1 Answer 1

1

Okay, let's say you have property getLevel() which would return your current item's level. Then in your Category entity file, create a simple method, for example getIndentedTitle thar would return your pre-defined category based on its level.

public function getIndentedTitle() {
    return sprintf(
        '%s %s',
         str_repeat('-', $this->getLevel()),
         $this->getTitle()
    );
}

The following code will add as many "-" symbols as your current category level and will append its title next to it.

Then in your form builder, you have to specify to use that method:

$builder->add('parent', 'entity', array('class' => 'AcmeBlogBundle:Category', 'property' => 'indentedTitle'));

More info on str_repeat.

Hope you got the idea.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.